C Program to perform Matrix Transpose

You are Here:

Perform Matrix Transpose

In the following example, we will transpose the given matrix (two-dimensional array).

Example

C Compiler
#include <stdio.h> int main() { int i, j, n; int arr[3][3] = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3} }; printf("Matrix (3 X 3):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr[i][j]); printf("\n"); } for(i=0; i<3; i++) { for(j=i+1; j<3; j++) { n = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = n; } } printf("\nMatrix Transpose:\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr[i][j]); printf("\n"); } return 0; }

Output

Matrix (3 X 3): 1 1 1 2 2 2 3 3 3 Matrix Transpose: 1 2 3 1 2 3 1 2 3

In the following example, we will get the values for (3 x 3) Matrix from the user and display the transpose matrix.

Example

C Compiler
#include <stdio.h> int main() { int i, j, n; int arr[3][3]; printf("Enter Matrix (3 X 3):\n"); for(i=0; i<3; i++) for(j=0; j<3; j++) scanf("%d", &arr[i][j]); for(i=0; i<3; i++) { for(j=i+1; j<3; j++) { n = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = n; } } printf("\nMatrix Transpose:\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d ", arr[i][j]); printf("\n"); } return 0; }

Output

Enter Matrix (3 X 3): 1 2 3 4 5 6 7 8 9 Matrix Transpose: 1 4 7 2 5 8 3 6 9

Reminder

Hi Developers, we almost covered 98% of String functions and Interview Question on C with examples for quick and easy learning.

We are working to cover every Single Concept in C.