# C++ Program to Find Transpose of a Matrix

C++ProgrammingServer Side Programming

A matrix is a rectangular array of numbers that is arranged in the form of rows and columns. A transpose of a matrix is a new matrix in which the rows of the original are the columns now and vice versa. For example.

A matrix is given below −

1 2 3
4 5 6
7 8 9

The transpose of the above matrix is as follows.

1 4 7
2 5 8
3 6 9

A program to find the transpose of a matrix is as follows −

## Example

Live Demo

#include<iostream<
using namespace std;
int main() {
int transpose, r=3, c=2, i, j;
int a = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
transpose[j][i] = a[i][j];
}
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
for(j=0; j<r; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
}
return 0;
}

## Output

The matrix is:
1 2
3 4
5 6

The transpose of the matrix is:
1 3 5
2 4 6

In the above program, the matrix is initialized. Then its values are displayed. This is shown in the following code snippet.

int a = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}

The transpose of the matrix is calculated using a nested for loop. This is given as follows.

for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
transpose[j][i] = a[i][j];
}

Finally, the transpose is obtained and it is printed on the screen. This is done with the following code snippet.

cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
for(j=0; j<r; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
}