How to transpose a matrix (swap rows and columns) in C#

1 Answer

0 votes
using System;

class Program
{
    // Function to transpose a matrix
    static int[,] Transpose(int[,] matrix)
    {
        int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);

        int[,] result = new int[cols, rows];

        for (int i = 0; i < cols; i++)
            for (int j = 0; j < rows; j++)
                result[i, j] = matrix[j, i];

        return result;
    }

    static void Main()
    {
        int[,] matrix = {
            {1, 2, 3, 5},
            {4, 5, 6, 1},
            {7, 8, 9, 0}
        };

        int[,] transposed = Transpose(matrix);

        int rows = transposed.GetLength(0);
        int cols = transposed.GetLength(1);

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++)
                Console.Write(transposed[i, j] + " ");
            Console.WriteLine();
        }
    }
}



/*
run:

1 4 7 
2 5 8 
3 6 9 
5 1 0 

*/

 



answered Jan 13, 2022 by avibootz
edited 1 day ago by avibootz
...