How to calculate transpose of a matrix using C program?

The transpose of a matrix is obtained by converting rows to columns and columns to rows. If A is an original matrix and B is its transpose, then element at position A[i][j] becomes B[j][i].

Syntax

for (i = 0; i < rows; i++)
    for (j = 0; j < cols; j++)
        transpose[j][i] = matrix[i][j];

Example 1: Dynamic Input Matrix

This example reads matrix dimensions and elements from user input −

#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:<br>");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    /* Calculate transpose */
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
    
    printf("\nOriginal matrix:<br>");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("<br>");
    }
    
    printf("\nTranspose of the matrix:<br>");
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
            printf("%d\t", transpose[i][j]);
        }
        printf("<br>");
    }
    
    return 0;
}
Enter rows and columns: 2 3
Enter elements of the matrix:
1 2 3
4 5 6

Original matrix:
1	2	3	
4	5	6	

Transpose of the matrix:
1	4	
2	5	
3	6	

Example 2: Using Predefined Matrix

This approach uses preprocessor directives to define matrix dimensions −

#include <stdio.h>
#define ROWS 3
#define COLS 2

int main() {
    int i, j;
    int matrix[ROWS][COLS] = {{1, 4}, {2, 5}, {3, 6}};
    int transpose[COLS][ROWS];
    
    /* Calculate transpose */
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
    
    printf("Original matrix (%dx%d):<br>", ROWS, COLS);
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("<br>");
    }
    
    printf("\nTranspose matrix (%dx%d):<br>", COLS, ROWS);
    for (i = 0; i < COLS; i++) {
        for (j = 0; j < ROWS; j++) {
            printf("%d ", transpose[i][j]);
        }
        printf("<br>");
    }
    
    return 0;
}
Original matrix (3x2):
1 4 
2 5 
3 6 

Transpose matrix (2x3):
1 2 3 
4 5 6 

Key Points

  • For an m×n matrix, the transpose will be n×m.
  • The element at matrix[i][j] moves to transpose[j][i].
  • Time complexity is O(m×n) where m and n are matrix dimensions.

Conclusion

Matrix transpose is a fundamental operation that swaps rows and columns. The algorithm involves nested loops to copy elements from position [i][j] to [j][i] in the transpose matrix.

Updated on: 2026-03-15T13:42:40+05:30

54K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements