Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate transpose of a Matrix.

C Code Example — Array Programs

ADVERTISEMENT

C Program to calculate transpose of a Matrix.

Objective

Write a C program to calculate the transpose of a Matrix.

Algorithm / Approach

  1. Declare a source matrix mat[3][2] and a destination matrix trans[2][3].
  2. Read the elements into the source matrix.
  3. Use nested loops to swap the rows and columns: trans[j][i] = mat[i][j].
  4. Print the transposed matrix using a loop where the outer limit is the columns and inner limit is the rows.
main.c
#include<stdio.h>
int main( ){
 int r=3, c=2, i, j;
 int mat[3][2], trans[2][3]; 
 printf("Enter elements of mat: ");
 for (i=0; i < r; i++){
  for(j=0; j < c; j++){
   scanf("%d",&mat[i][j]);
  }
 }
 for (i=0; i < r; i++){
  for( j=0 ; j < c ; j++ ){
   trans[j][i] = mat[i][j];
  }
 }
  printf("Transpose of Matrix: ");
  for (i = 0; i < c; i++){
   for (j = 0; j < r; j++){
    printf("%d  ",trans[i][j]);
   }
  printf("\n");
}
 return 0;
}

Expected Output

Enter elements of Mat : 
1 2
3 4
5 6
Transpose of Matrix : 
1  3  5
2  4  6

Explanation of the Program

  • The Transpose of a matrix is formed by turning all the rows into columns and all the columns into rows.
  • If the original matrix had dimensions of 3 rows by 2 columns, the transposed matrix will automatically have dimensions of 2 rows by 3 columns. We achieve this by simply flipping the i and j indexes during assignment.

Complexity

Time Complexity O(r * c)
Space Complexity O(r * c)
ADVERTISEMENT