# How to calculate transpose of a matrix using C program?

CServer Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

## Transpose of a matrix

The transpose of a matrix is the one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of the matrix B are the columns of the matrix A then Matrix B is said to be the transpose of Matrix A.

The logic used to change m(i,j) matrix to m(j,i) is as follows −

for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];

## Program 1

In this example, we shall print the transpose of a matrix using for loop.

Live Demo

#include <stdio.h>
int main(){
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter rows and columns :\n");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
printf("Transpose of the matrix:\n");
for (i = 0; i< n; i++) {
for (j = 0; j < m; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
return 0;
}

## Output

Enter rows and columns :
2 3
Enter elements of the matrix
1 2 3
2 4 5
Transpose of the matrix:
1    2
2    4
3    5

## Program 2

Live Demo

#include<stdio.h>
#define ROW 2
#define COL 5
int main(){
int i, j, mat[ROW][COL], trans[COL][ROW];
printf("Enter matrix: \n");
// input matrix
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
scanf("%d", &mat[i][j]);
}
}
// create transpose
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
trans[j][i] = mat[i][j];
}
}
printf("\nTranspose matrix: \n");
// print transpose
for(i = 0; i < COL; i++){
for(j = 0; j < ROW; j++){
printf("%d ", trans[i][j]);
}
printf("\n");
}
return 0;
}

## Output

Enter matrix:
1 2 3 4 5
5 4 3 2 1

Transpose matrix:
1 5
2 4
3 3
4 2
5 1
Updated on 05-Mar-2021 10:44:53