This program finds the transpose of a given 2-D matrix (rows become columns and columns become rows).
C Program
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10];
int m, n, i, j;
printf("Enter number of rows (m) and columns (n): ");
scanf("%d %d", &m, &n);
printf("Enter elements of the matrix:\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
transpose[j][i] = a[i][j];
printf("Transpose of the matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
- The transpose of an m x n matrix is an n x m matrix where element
[i][j]of the original becomes element[j][i]of the result. - The assignment
transpose[j][i] = a[i][j]does exactly this swap of row/column indices while copying. - Since the transpose has swapped dimensions, the printing loops iterate up to
nrows andmcolumns instead of the originalmandn.
Sample Output
Enter number of rows (m) and columns (n): 2 3
Enter elements of the matrix:
1 2 3
4 5 6
Transpose of the matrix:
1 4
2 5
3 6