Transpose of Matrix in C++
Program to find the transpose of matrix
Here, in this section we will find the transpose of the matrix in C++ .
Transpose of a matrix is obtained by interchanging rows and columns. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].
Example :
A transpose of a matrix is the matrix flipped over its diagonal i.e. the row and column indices of the matrix are switched. An example of this is given as follows −
Matrix = 1 2 3 4 5 6 7 8 9
Transpose of Matrix = 1 4 7 2 5 8 3 6 9
Algorithm :
Transpose of the matrix in C++ can be achieved by doing so ,
- Take the number of rows and column for the matrix from the user
- Take the input of matrix from the user.
- For transpose, we can print the matrix by interchanging row and column
Code in C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
int r, c;
cout<<“Enter rows and columns of matrix: “;
cout<<r<<c;
int a[r][c];
cout<<“\nEnter elements of matrix:”;
for(int i=0; i<r; i++){
for(int j=0; j<c; j++)
cin>>a[i][j];
}
// Displaying the matrix a[][] */
cout<<“\nEntered Matrix: \n”;
for(int i=0; i<r; i++){
for(int j=0; j<c; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
// Displaying the transpose of matrix a
cout<<“\nTranspose of Matrix:\n”;
for(int i=0; i<c; i++){
for(int j=0; j<r; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
return 0;
}
Output :
Enter rows and columns of matrix : 3 3
Enter elements of matrix :
1 2 3
4 5 6
7 8 9
Displaying the matrix :
1 2 3
4 5 6
7 8 9
Transpose of Matrix :
1 4 7
2 5 8
3 6 9