Transpose matrix in C with example

Transpose matrix in C with example

In this tutorial, you will learn a writing program of Transpose matrix in C with example.

To learn writing a program for finding transpose of a matrix, you should have some knowledge of

  • Array and
  • Multidimensional Array

Also, Writing the program of Transpose matrix in C with example is not that much tough.

We can obtain transpose of a matrix by exchanging the rows and columns. Matrix made with the help of rows and columns or we can say that every matrix has row and column. Now if you want to generate the transpose of the matrix you don’t have to do anything, just exchange rows element into column and column elements into a row.

Below is the c program to find the transpose of a matrix where the user is asked to enter the number of rows r and columns c. Their values should be less than 5 in this program.

Then, the user is asked to enter the elements of the matrix (of order r*c).

C Program to Print transpose of matrix

[c] #include <stdio.h> int main() { int a[5][5], transpose[5][5], r, c, i, j; printf("Please enter number of rows and columns: "); scanf("%d %d", &r, &c); printf("\nEnter matrix elements:\n"); for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) { printf("Enter element a%d%d: ", i + 1, j + 1); scanf("%d", &amp;a[i][j]); } // Showing the matrix a[][] printf("\nEntered matrix: \n"); for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) { printf("%d ", a[i][j]); if (j == c – 1) printf("\n"); } // Finding the transpose of matrix a for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) { transpose[j][i] = a[i][j]; } // showing the transpose of matrix a printf("\nTranspose of the matrix:\n"); for (i = 0; i < c; ++i) for (j = 0; j < r; ++j) { printf("%d ", transpose[i][j]); if (j == r – 1) printf("\n"); } return 0; } [/c]

Output

C Program to Find Transpose of a Matrix

Above Program Explanation of transpose matrix

In the above program we have taken two matrix name is “x” and “transpose” having five rows and columns in each.

Now with the help of for loop I have tried to insert values in each rows and columns. Now its time to shift all rows elements in columns and each columns into rows.

[c]transpose[j][i] = a[i][j];[/c]

Above code is doing the rows into column movement.

Thanks for reading 🙂