In this shot, we will go over how to find the transpose of a two-dimensional array (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.
Since we are using a 2-D array, we need to use a nested for
loop to traverse through it.
for
loop. The outer for
loop will iterate through rows and the inner loop will iterate through columns.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.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 formatvoid 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 matrixconst 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 sizeint transpose[rows][columns];cout << "Original Matrix: " << endl;printArr(arr, columns);// outer for loop to traverse rowsfor(int i = 0; i < rows; i++){// inner for loop to traverse columnfor(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;}