How to calculate transpose of a matrix using C program?


Transpose of a matrix

The transpose of a matrix is the one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of the matrix B are the columns of the matrix A then Matrix B is said to be the transpose of Matrix A.

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];

Program 1

In this example, we shall print the transpose of a matrix using for loop.

 Live Demo

#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; }

Output

Enter rows and columns :
2 3
Enter elements of the matrix
1 2 3
2 4 5
Transpose of the matrix:
1    2
2    4
3    5

Program 2

 Live Demo

#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; }

Output

Enter matrix:
1 2 3 4 5
5 4 3 2 1

Transpose matrix:
1 5
2 4
3 3
4 2
5 1

Updated on: 02-Sep-2023

46K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements