Transpose of a Matrix in C

This blog post will teach you how to Transpose a Matrix in C with a programming example. You can obtain the “transpose” of a matrix by swapping the rows with columns and vice-versa.

For example,

Input: mat[][] = 8   2   13
                 14  15  6
                 3   8   9


Output: 8  14  13
        2  15  8
        13  6  9

 

The primary prerequisite to understanding the below example code:

 

C Program to Transpose of a Matrix:

In this example, we are taking a square matrix of order 3×3. The order of the transposed matrix would be 3×3.

#include <stdio.h>

#define C 3


void transposeMatrix(int mat[][C], int transposedMat[][C])
{
    int row, col;
    for (row = 0; row < C; row++)
    {
        for (col = 0; col < C; col++)
        {
            transposedMat[row][col] = mat[col][row];
        }
    }
}

int main()
{
    int i, j;
    int mat[3][3], transposedMat[3][3];

    printf("Enter elements of Matrix\n");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            printf("Enter the elements of matrix P [%d,%d]: ", i, j);
            scanf("%d", &mat[i][j]);
        }
    }

    //call the function to transpose
    transposeMatrix(mat, transposedMat);

    printf("Transpose of matrix is:\n\n");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            printf("%d ", transposedMat[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter elements of Matrix

Enter the elements of matrix P [0,0]: 1
Enter the elements of matrix P [0,1]: 2
Enter the elements of matrix P [0,2]: 3
Enter the elements of matrix P [1,0]: 4
Enter the elements of matrix P [1,1]: 5
Enter the elements of matrix P [1,2]: 6
Enter the elements of matrix P [2,0]: 7
Enter the elements of matrix P [2,1]: 8
Enter the elements of matrix P [2,2]: 9


Transpose of matrix is:

1 4 7
2 5 8
3 6 9

 

How the above program works:

  • Created two matrices “mat” and “transposedMat”.
  • Start traversing the mat row-wise.
  • Copy all elements of the first row of the mat to the first column of transposedMat.
  • Repeat the process for all rows and at the end of the process, the transposedMat will be a transpose of the mat.

 

Recommended Post: