Javatpoint Logo
Javatpoint Logo

Transpose of Matrix in C

In linear algebra, the transpose of a matrix is a new matrix that is obtained by interchanging its rows and columns. For example, if we have a matrix A with dimensions m x n, then its transpose AT will have dimensions n x m.

To transpose a matrix in C programming language, we can follow the following steps:

Declare the matrix: First, we need to declare a two-dimensional array to represent our matrix. We can do this by specifying the number of rows and columns as follows:

Here, m and n represent the number of rows and columns, respectively.

Initialize the matrix: Next, we need to initialize the matrix with some values. We can do this using a nested for loop as follows:

Here, we are using the scanf function to input values into the matrix.

Transpose the matrix: Once we have our matrix initialized, we can transpose it using another nested for loop as follows:

Here, we are swapping the elements of the matrix along the diagonal. This is done by storing the value of the element at matrix[i][j] in a temporary variable, swapping the values of matrix[i][j] and matrix[j][i], and then assigning the value of the temporary variable to matrix[j][i].

Display the transposed matrix: Finally, we can display the transposed matrix using another nested for loop as follows:

Here, we are using the printf function to display the elements of the transposed matrix.

Putting it all together, we get the following complete program:

C Program:

Output:

Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
1 2
2 3
3 4
The transposed matrix is:
1 2 3 
2 3 4

This program prompts the user to input the dimensions of the matrix, initializes the matrix with user input values, transposes the matrix, and then displays the transposed matrix to the user. Note that the program assumes that the user inputs valid values for the dimensions of the matrix and for the elements of the matrix.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA