C# program to transpose a matrix

Here, we are going to learn how to transpose a matrix in C#?
Submitted by Nidhi, on November 02, 2020 [Last updated : March 19, 2023]

Transposing a matrix

Here, we will read a matrix from the user and then transpose the matrix. The transpose of the matrix means, here we replace the rows by columns in the matrix.

Algorithm/Steps

The steps to transpose a matrix in C# are:

  • Create a matrix i.e., a two-dimensional array.
  • Input the matrix elements.
  • To transpose a matrix, just use two loops. Run the outer loop till columns and the inner loop till rows.
  • It will print the transpose of a matrix.

C# program to transpose a matrix

The source code to transpose a matrix is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to transpose a matrix.

using System;

class MatrixDemo
{
    public static void Main(string[] args)
    {
        int i = 0;
        int j = 0;

        int row = 2;
        int col = 2;

        int[,] Matrix= new int[row, col];
        
        Console.Write("Enter the elements of matrix: ");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
                Matrix[i, j] = int.Parse(Console.ReadLine());
            }
        }
        
        Console.WriteLine("\nMatrix: ");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
                Console.Write(Matrix[i, j] + "\t");

            }
            Console.WriteLine();
        }
        
        Console.WriteLine("Transpose of matrix : ");
        for (i = 0; i < col; i++)
        {
            for (j = 0; j < row; j++)
            {
                Console.Write(Matrix[j, i] + "\t");

            }
            Console.WriteLine();
        }
    }
}

Output

Enter the elements of matrix: 1
2
3
4

Matrix:
1       2
3       4
Transpose of matrix :
1       3
2       4
Press any key to continue . . .

Explanation

In the above program, we created a class MatrixDemo that contains a Main() method. The Main() method is the entry point for the program, Here, we created a 2-D array to represent a matrix with size 2X2. Then we read elements of the matrix form user and then print the transpose of the matrix by replacing rows by columns.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.