Transpose of a Matrix in C

Problem Statement: Given a Matrix print the transpose of a matrix.

Examples:

Example 1:
Input: mat[][] = 1 2 3
                 4 5 6
                 7 8 9
Output: 1 4 7
        2 5 8
        3 6 9

Example 2:
Input: mat[][] = 10 20 30
                 40 50 60
                 70 80 90
Output: 10 40 70
        20 50 80
        30 60 90

DisclaimerDon’t jump directly to the solution, try it out yourself first.

What is a transpose of a Matrix?

The transpose of a matrix is obtained by interchanging the rows and columns of the original matrix.

The rows of the original matrix become columns of the transpose matrix and the columns of the original matrix become rows of the transpose matrix.

How to transpose a matrix?

  • Create a new matrix
  • Start traversing the current matrix row-wise.
  • Copy all elements of first row of input matrix to first column of new matrix.
  • Repeat the process for all rows in the input matrix for consecutive columns of the new matrix.
  • At the end of the process, the new matrix will be a transpose of input matrix.

Code:

C Program

#include <stdio.h>
#define N 3

void transpose(int mat1[][N], int mat2[][N])
{
	int i, j;
	for (i = 0; i < N; i++)
		for (j = 0; j < N; j++)
			mat2[i][j] = mat1[j][i];
}

int main()
{   
    
	int mat1[N][N] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

	int mat2[N][N], i, j;

	transpose(mat1, mat2);

	printf("Transposed matrix is: \n");
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		printf("%d ", mat2[i][j]);
		printf("\n");
	}

	return 0;
}

Output:

Transposed matrix is:
1 4 7
2 5 8
3 6 9

Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article