Algorithm
Here's the algorithm for finding the transpose of a matrix without the C code:
1. Input:
- Take input for the number of rows and columns of the matrix.
2. Matrix Input:
- Input the elements of the matrix.
3. Transpose Calculation:
- Create a new matrix (transposed matrix) with dimensions swapped (rows become columns and vice versa).
- Use nested loops to iterate over each element of the original matrix.
- Place the element in the transposed matrix at the corresponding swapped position (i, j becomes j, i).
**The logic used to change m(i,j) matrix to m(j,i) is as follows −
for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
4. Output:
- Display the transposed matrix.
Code Examples
#1 Code Example-We shall print the transpose of a matrix using for loop.
Code -
C Programming
#include <stdio.h>
int main(){
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter rows and columns :
");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix
");
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
printf("Transpose of the matrix:
");
for (i = 0; i< n; i++) {
for (j = 0; j < m; j++)
printf("%d\t", transpose[i][j]);
printf("
");
}
return 0;
}
Copy The Code &
Try With Live Editor
Output
2 3
Enter elements of the matrix
1 2 3
2 4 5
Transpose of the matrix:
1 2
2 4
3 5
#2 Code Example-C Programing to Find Transpose of a Matrix
Code -
C Programming
#include<stdio.h>
#define ROW 2
#define COL 5
int main(){
int i, j, mat[ROW][COL], trans[COL][ROW];
printf("Enter matrix:
");
// input matrix
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
scanf("%d", &mat[i][j]);
}
}
// create transpose
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
trans[j][i] = mat[i][j];
}
}
printf("
Transpose matrix:
");
// print transpose
for(i = 0; i < COL; i++){
for(j = 0; j < ROW; j++){
printf("%d ", trans[i][j]);
}
printf("
");
}
return 0;
}
Copy The Code &
Try With Live Editor
Output
1 2 3 4 5
5 4 3 2 1
Transpose matrix:
1 5
2 4
3 3
4 2
5 1
Demonstration
C Programing Example to Find Transpose of a Matrix-DevsEnv