How to find transpose of a 2D Matrix in C++

In this shot, we will go over how to find the transpose of a two-dimensional array (matrix).

What is the transpose of a matrix?

The transpose of a matrix is taken by switching the columns and rows of a matrix. Specifically, the matrix is flipped along its diagonal. The diagonal will remain the same.

Explanation of the code:

Since we are using a 2-D array, we need to use a nested for loop to traverse through it.

  1. First, initialize your 2-D array.
  2. Run a nested for loop. The outer for loop will iterate through rows and the inner loop will iterate through columns.
  3. While accessing element arr[row][col], insert the element into transpose[col][row], i.e., switch the rows and columns. For example,
    arr[0][1] will be placed at transpose[1][0], so two and four will swap positions in the transpose matrix.
  4. The for loop will iterate through every element and insert it into the correct index in the transpose 2-D array.
#include<iostream>
using namespace std;
// user defined function to print 2 day array with correct format
void printArr (int arr[][3], int columns)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < columns; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main()
{
// declare matrix
const int rows = 3;
const int columns = 3;
int arr[rows][columns] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
// declare transpose matrix of same size
int transpose[rows][columns];
cout << "Original Matrix: " << endl;
printArr(arr, columns);
// outer for loop to traverse rows
for(int i = 0; i < rows; i++)
{
// inner for loop to traverse column
for(int j = 0; j < columns; j++)
{
// insert arr[row][col] to transpose[col][row]
transpose[j][i] = arr[i][j];
}
}
cout<< "Transpose Matrix: " << endl;
printArr(transpose, columns);
return 0;
}

Free Resources