WAP to transpose two matrix
Objective
Write a C++ program to calculate the transpose of a Matrix.
Algorithm / Approach
- Declare a source matrix
mat[3][2]and a destination matrixtran[2][3]. - Read elements into the source matrix.
- Use nested loops to assign rows to columns and columns to rows:
tran[j][i] = mat[i][j]. - Print the transposed matrix.
main.cpp
#include<iostream>
using namespace std;
int main() {
int mat[3][2],tran[2][3];
cout<<"Enter Elements of Mat: \n";
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 2; j++) {
cin>>mat[i][j];
tran[j][i] = mat[i][j];
}
}
cout<<"Transpose of Matrix: \n";
for(int i = 0; i< 2; i++) {
for(int j = 0; j< 3; j++) {
cout<< tran[i][j]<<" ";
}
cout<< endl;
}
return 0;
}
Expected Output
Enter Elements of Mat 3 4 2 3 6 8 Transpose of Matrix: 3 2 6 4 3 8
Explanation of the Program
- The Transpose of a matrix is formed by turning all the rows into columns and all the columns into rows.
- If the original matrix had dimensions of 3 rows by 2 columns, the transposed matrix automatically has dimensions of 2 rows by 3 columns. We achieve this by flipping the
iandjarray indexes during the assignment.
Complexity
Time Complexity
O(r * c)
Space Complexity
O(r * c)