Explanation
Transposing a matrix is also known as flipping a matrix where rows become columns and columns become rows,
In other words, lets M[a][b] is a matrix and Transpose of it is M[b][a].
Where,
For Example:
This question was asked in the Zoho interview.
by solving this problem, you will also learn about multidimensional array. Check list of coding questions on Array.
Prerequisites:
Code:
You can execute this program using our CSEstack online IDE.
#include<stdio.h>
int main()
{
int a[3][2],b[2][3], i, j;
//take user input
printf("Enter value for matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
//print origional matrix
printf("Matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf(" %d ",a[i][j]);
printf("\n");
}
//find the transpose of the matrix
for(i=0; i<3; i++)
{
for(j=0; j<2; j++)
b[j][i] = a[i][j];
}
//print transposed matrix
printf("Transpose matrix:\n");
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
printf(" %d ", b[i][j]);
printf("\n");
}
return 0;
}
Output:
Enter value for matrix: Matrix: 1 2 3 4 5 6 Transpose matrix: 1 3 5 2 4 6
Just like any for loop, you can also use the while or do-while loop to solve this problem.
You can also this program to find the transpose of a matrix in any other programming language as C/C++, Java or Python. Give it a try.