Transpose a matrix in C#

CsharpProgrammingServer Side Programming

Transpose of a matrix flips the matrix over its diagonal and this brings the row elements on the column and column elements on the row.

For example −

Matrix before Transpose:

123
456
789

Matrix after Transpose:
147
258
369

Let us see an example in C# to achieve transpose of a matrix −

Example

using System;
public class Demo {
   public static void Main() {
      int i, j, m, n;
      int[, ] arr1 = new int[30, 30];
      int[, ] arr2 = new int[30, 30];

      Console.Write("\nEnter the number of rows and columns of the matrix :\n");
      Console.Write("Rows entered = ");
      m = Convert.ToInt32(Console.ReadLine());

      Console.Write("Columns entered = ");
      n = Convert.ToInt32(Console.ReadLine());

      Console.Write("Set elements in the matrix...\n");
      for (i = 0; i < m; i++) {
         for (j = 0; j < n; j++) {
            Console.Write("\n [{0}],[{1}] : ", i, j);
            arr1[i, j] = Convert.ToInt32(Console.ReadLine());
         }
      }

      Console.Write("\n\nMatrix before Transpose:\n");
      for (i = 0; i < m; i++) {
         Console.Write("\n");
         for (j = 0; j < n; j++)
         Console.Write("{0}\t", arr1[i, j]);
      }

      for (i = 0; i < m; i++) {
         for (j = 0; j < n; j++) {

            arr2[j, i] = arr1[i, j];
         }
      }

      Console.Write("\n\nMatrix after Transpose: ");
      for (i = 0; i < m; i++) {
         Console.Write("\n");
         for (j = 0; j < n; j++) {
            Console.Write("{0}\t", arr2[i, j]);
         }
      }
      Console.Write("\n\n");
   }
}

The following result will be produced on running the above program. Here, values from the user are to be entered for number of rows and columns, and the elements of the matrix −

Enter the number of rows and columns of the matrix :3 3
Rows entered = 3
Columns entered 3
Set elements in the matrix...

[0],[0] : 1
[0],[1] : 2
[0],[2] : 3
[1],[0] : 4
[1],[1] : 5
[1],[2] : 6
[2],[0] : 7
[2],[1] : 8
[2],[2] : 9

Matrix before Transpose:

123
456
789

Matrix after Transpose:
147
258
369
raja
Published on 13-Aug-2018 12:57:20
Advertisements