Transpose a Matrix in C++

Exercise:

Write a C++ program can transpose a matrix.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main() 
{
    int a[10][10], trans[10][10], row, col, i, j;
    cout << "Insert rows and columns of matrix:\n";
    cin >> row >> col;
    cout << "\nInsert values of matrix:\n" << endl;
    for (int i = 0; i < row; ++i)   // Storing
        for (int j = 0; j < col; ++j)
        {
            cout << "position " << i + 1 << j + 1 << ": ";
            cin >> a[i][j];
        }
    cout << "\nInserted Matrix: " << endl;
    for (int i = 0; i < row; ++i) 
        for (int j = 0; j < col; ++j)
        {
            cout << " " << a[i][j];
            if (j == col - 1)
            cout << endl;
        }
    // Computing trans of the matrix
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j)
        {
            trans[j][i] = a[i][j];
        }
    // Printing
    cout << "\nTranspose of the Matrix: " << endl;
    for (int i = 0; i < col; ++i)
        for (int j = 0; j < row; ++j)
        {
            cout << " " << trans[i][j];
            if (j == row - 1)
            cout << endl;
        }
    return 0;
}
Click Here to View the Output:
Insert rows and columns of matrix:
 2
 3
 Insert values of matrix:
 position 11: 2
 position 12: 4
 position 13: 5
 position 21: 2
 position 22: 1
 position 23: 3
 Inserted Matrix:
  2 4 5
  2 1 3
 Transpose of the Matrix:
  2 2
  4 1
  5 3
Click Here to View the Explanation:
  • Some variables are initialized and the number of rows and columns for the matrix is limited to 10 maximum.
  • User is requested to enter the number of rows row and number of columns col.
  • for loop is used to input the elements of a matrix. Another for loop is used to display the matrix on the screen.
  • 3rd for loop is used to calculate the transpose of the matrix.
  • 4th for loop prints the transpose on the screen.