Transpose of matrix in C++
Written by
The transpose of a matrix is obtained by interchanging its rows and column.
Algorithm:
1. Take input for number of rows and columns.
2. Interchange rows and columns.
Below given code doesn’t use functions. It can also be written using functions.
Code:
#include<iostream> using namespace std; int row,col; int main() { int val,row,col; //insert rows and columns for matrix cin>>row; cin>>col; int a[row][col]; //insert values in the matrix cout<<"\n a: \n"; for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { cin>>val; a[i][j]=val; } }
//puting content of rows of a in columns of b int b[col][row]; for(int j=0;j<row;j++) { for(int i=0;i<col;i++) b[i][j]=a[j][i]; }
//copy contents of b in a for(int i=0;i<col;i++) { for(int j=0;j<row;j++) a[i][j]=b[i][j]; }
//display a for(int i=0;i<col;i++) { for(int j=0;j<row;j++) cout<<a[i][j]<<" "; cout<<"\n"; } return 0;
}
Output:
3 3
1 2 3 4 5 6 7 8 9
a: 1 4 7 2 5 8 3 6 9