Home »
C programs »
C two-dimensional arrays programs
C program to transpose a matrix
Here, we are going to learn how to read a matrix and prints the transpose the matrix.
Problem statement
Given a matrix, write a C program to transpose the given matrix.
Transposing a matrix
To transpose a matrix, swap its rows and columns. That means the first row becomes the first column, and the second row becomes the second column, and so on. Thus, you have to flip the matrix over its diagonal to make the rows into columns and columns into rows.
C program to transpose a matrix
This program will read a matrix and prints the transpose matrix:
#include <stdio.h>
#define MAXROW 10
#define MAXCOL 10
int main()
{
int matrix[MAXROW][MAXCOL];
int i,j,r,c;
printf("Enter number of Rows :");
scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);
printf("\nEnter matrix elements :\n");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
}
/*Transpose a matrix */
printf("\nTranspose Matrix is :");
for(i=0;i< c;i++)
{
for(j=0;j< r;j++)
{
printf("%d\t",matrix[j][i]); /*print elements*/
}
printf("\n"); /*after each row print new line*/
}
return 0;
}
Output
Enter number of Rows :2
Enter number of Cols :3
Enter matrix elements :
Enter element [1,1] : 1
Enter element [1,2] : 2
Enter element [1,3] : 3
Enter element [2,1] : 4
Enter element [2,2] : 5
Enter element [2,3] : 6
Transpose Matrix is :
1 4
2 5
3 6
Read Rows and Columns for Matrix
To read number of rows and columns for the matrix, use the following code:
printf("Enter number of Rows :");
scanf("%d", &r);
printf("Enter number of Cols :");
scanf("%d", &c);
Reading Matrix
After reading number of rows and columns, you need to input a matrix. Here is the code to read a matrix of R x C, where R is the number of rows and C is the number of columns.
printf("\nEnter matrix elements :\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
printf("Enter element [%d,%d] : ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
Transposing Matrix
The below code prints the transpose matrix:
printf("\nTranspose Matrix is :");
for (i = 0; i < c; i++) {
for (j = 0; j < r; j++) {
printf("%d\t", matrix[j][i]); /*print elements*/
}
printf("\n"); /*after each row print new line*/
}
C Two-dimensional Arrays Programs »