Trusted answers to developer questions

Sarah Tanveer

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.

- First, initialize your 2-D array.
- Run a nested
`for`

loop. The outer`for`

loop will iterate through rows and the inner loop will iterate through columns. - 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. - 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; }

RELATED TAGS

transpose

c++

matrix

communitycreator

CONTRIBUTOR

Sarah Tanveer

RELATED COURSES

View all Courses

Keep Exploring

Related Courses