C++ Program to Find Transpose of a Matrix

  • How to find transpose of a matrix in C++.
  • Write a C++ program to print transpose matrix.

C++ Program to find transpose matrix

#include <iostream>

using namespace std;
 
int main(){
    int rows, cols, r, c;
    int inputMatrix[50][50], transposeMatrix[50][50];
    cout << "Enter Rows and Columns of Matrix" << endl;
    cin >> rows >> cols;
     
    cout << "Enter Matrix of size "<< rows << " X " << cols << endl;
     
    for(r = 0; r < rows; r++){
        for(c = 0; c < cols; c++){
            cin >> inputMatrix[r][c];
        }
    }
     
    // transposeMatrix[r][c] = inputMatrix[c][r]
    for(r = 0; r < rows; r++){
        for(c = 0; c < cols; c++){
            transposeMatrix[c][r] = inputMatrix[r][c];
        }
    }
     
    cout << "Transpose Matrix" << endl;
    // Transpose Matrix of MXN  =  NXM Matrix 
    for(r = 0; r < cols; r++){
        for(c = 0; c < rows; c++){
            cout << transposeMatrix[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

Output
Enter Rows and Columns of Matrix
3 3
Enter Matrix of size 3 X 3
1 2 3
4 5 6
7 8 9
Transpose Matrix
1 4 7
2 5 8
3 6 9