The Program in C# Program to Find Transpose of Given Matrix is given below:
using System;
namespace MatrixTranspose
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the number of rows and columns in the matrix: ");
int rows = int.Parse(Console.ReadLine());
int columns = int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, columns];
int[,] transpose = new int[columns, rows];
Console.WriteLine("Enter the elements of the matrix: ");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
matrix[i, j] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
transpose[j, i] = matrix[i, j];
}
}
Console.WriteLine("Okay, the transpose of the matrix is: ");
for (int i = 0; i < columns; i++)
{
for (int j = 0; j < rows; j++)
{
Console.Write(transpose[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output:
Hello Codeauri Family, enter the number of rows and columns in the matrix:
2
2
Enter the elements of the matrix:
4
1
2
5
Okay, the transpose of the matrix is:
4 2
1 5
Pro-Tips💡
Here are the steps by steps execution of above program:
- The first line of the program using System; brings in the System namespace which contains the Console class used for input and output in the program.
- In the Main method, the program first prompts the user to enter the number of rows and columns in the matrix. It stores the values in the variables “rows” and “columns”.
- Then, it creates two two-dimensional arrays: “matrix” and “transpose”. “matrix” is initialized with the given number of rows and columns and “transpose” is initialized with the number of columns and rows (since the number of rows and columns in the transpose of a matrix are swapped).
- Next, the program prompts the user to enter the elements of the matrix and stores them in the “matrix” array.
- In the following step, the program calculates the transpose of the matrix. It does this by switching the values of the rows and columns in the “matrix” array and storing the result in the “transpose” array.
- Finally, the program outputs the transpose of the matrix by printing the elements of the “transpose” array.
- The program ends with the closing brace of the Main method.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.