ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-202 min read

Compute the transpose of a matrix in C by swapping row and column indices. Complete runnable C code and square matrix in-place swap logic.

What is a Matrix Transpose?

The transpose of an R × C matrix A, denoted Aᵀ, is a $C × R$ matrix formed by turning all rows of A into columns and all columns into rows:

text (ISO Standard)
A^T[j][i] = A[i][j]

C Code Implementation

c (ISO Standard)
#include <stdio.h>

#define ROWS 2
#define COLS 3

void transposeMatrix(int src[ROWS][COLS], int dest[COLS][ROWS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            dest[j][i] = src[i][j];
        }
    }
}

int main() {
    int matrix[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    int transposed[COLS][ROWS];
    transposeMatrix(matrix, transposed);

    printf("Original Matrix (%dx%d):\n", ROWS, COLS);
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    printf("\nTransposed Matrix (%dx%d):\n", COLS, ROWS);
    for (int i = 0; i < COLS; i++) {
        for (int j = 0; j < ROWS; j++) {
            printf("%d ", transposed[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

text (ISO Standard)
Original Matrix (2x3):
1 2 3 
4 5 6 

Transposed Matrix (3x2):
1 4 
2 5 
3 6 

Complexity Analysis

  • Time Complexity: O(R × C) to copy and transform all elements.
  • Space Complexity: O(C × R) to store transposed matrix.

Related C Examples & Tutorials