C++ Program to find the Transpose of a Matrix

In this tutorial, we will learn and write a program to find the transpose of matric in C++. Before that, you may go through the following topics in C++ programming:

The program takes the user input for the number of rows and columns and then the elements for the matrix.


C++ Program to find the Transpose of a Matrix

Program: Transpose of a matrix in C++ using array.

#include <iostream>
using namespace std;

int main()
{
  int arr[10][10], trans[10][10], row, col, i, j;

  cout << "Enter the no. of rows: ";
  cin >> row;
  cout << "Enter the no. of columns: ";
  cin >> col;

  //get matrix elements
  cout << "Enter the elements: " << endl;
  for (i = 0; i < row; i++)
  {
    for (j = 0; j < col; j++)
      cin >> arr[i][j];
  }

  // transpose computation
  for (i = 0; i < row; ++i)
    for (j = 0; j < col; ++j)
      trans[j][i] = arr[i][j];

  //Displaying the result
  cout << "\nTranspose result:" << 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 << endl;
    }

  return 0;
}

Output:

Enter the no. of rows: 3
Enter the no. of columns: 3
Enter the elements:
1 2 3
4 5 6
7 8 9

Transpose result:
1 4 7
2 5 8
3 6 9