# Transpose a matrix in C#

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("Enter the number of rows and columns of the matrix :");
Console.Write("Rows entered = ");

Console.Write("Columns entered = ");

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

Console.Write("Matrix before Transpose:");
for (i = 0; i < m; i++) {
Console.Write("");
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("Matrix after Transpose: ");
for (i = 0; i < m; i++) {
Console.Write("");
for (j = 0; j < n; j++) {
Console.Write("{0}\t", arr2[i, j]);
}
}
Console.Write("");
}
}

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...

, : 1
, : 2
, : 3
, : 4
, : 5
, : 6
, : 7
, : 8
, : 9

Matrix before Transpose:

123
456
789

Matrix after Transpose:
147
258
369