Transpose of a Matrix

Transpose of a matrix” is a basic problem on matrix where we interchange the row and columns with each other. Here, we are given a matrix of size N*M and our task is to find the transpose of the matrix by interchanging the row and columns.

Example:

N = 3, M = 2

12
34
56
MATRIX

135
246
Transposed Matrix

C++ Program to find transpose of a matrix is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  

{  
    int N,M;  
    // Scan Dimensions of the matrix  
    cout<<"Enter the dimensions of the matrix: ";  
    cin>>N>>M;  
      
    int matrix[N][M];  
    int transpose[M][N];  
      
    // Scan Matrix Elements  
    cout<<"Enter the elements of first matrix:";  
    for(int i = 0 ; i < N ; i++)  
    for(int j = 0 ; j < M ; j++)  
    cin>>matrix[i][j];  
      
    // Transpose Matrix  
    for (int i = 0; i < N; ++i)   
    for (int j = 0; j < M; ++j)   
    transpose[j][i] = matrix[i][j];  
  
    //Print Transposed matrix  
    cout<<"The Transposed Matrix is:\n";  
    for(int i = 0 ; i < M ; i++)  
    {  
        for(int j = 0 ; j < N ; j++)  
        {  
            cout<<transpose[i][j]<<" ";  
        }  
        cout<<endl;  
    }  
}  


OUTPUT:
Enter the dimensions of the matrix:
3 2
Enter the elements of matrix:
1 2
3 4
5 6
The Transposed Matrix is:
1 3 5 
2 4 6

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *