Kat H.

asked • 05/17/21

Transpose. Write code for the function transpose.

Write code for the function transpose. It should take the matrix given and produce the transpose by swapping rows and columns.

For the matrix shown here:

1 2 3
4 5 6
7 8 9


Your code should produce:

1 4 7
2 5 8
3 6 9


Hints:

  1. To swap two locations, you need to use a temp variable: temp = location1; location1 = location2; location2 = temp.
  2. You only should use the usual two loops - when you are on [i][j] it needs to swap with [j][i]
  3. If you swap [2][1] with [1][2] you want to make sure not to swap [1][2] with [2][1] or you just undo the swap! Stay on one side of the diagonal - practice by writing nested loops that print something like:
0
0 0
0 0 0
  1. Those spots mark the locations we would actually want to swap in a 3x3 matrix. The triangle printing problem back in NestedLoops works just like this...

Code:

#include <iostream>


using namespace std;


const int NUM_ROWS = 3;

const int NUM_COLS = 3;


void transpose(int matrix[NUM_ROWS][NUM_COLS]) {


//Do not modify anything on or above the line below this

//YOUR_CODE_BELOW


//YOUR_CODE


//YOUR_CODE_ABOVE

//Do not modify anything on or below the line above this


}


int main()

{

int nums[NUM_ROWS][NUM_COLS];

//Read in values

for(int i = 0; i < NUM_ROWS; i++) {

for(int j = 0; j < NUM_COLS; j++) {

cin >> nums[i][j];

}

}


transpose(nums);


for(int i = 0; i < NUM_ROWS; i++) {

for(int j = 0; j < NUM_COLS; j++) {

cout << nums[i][j] << " ";

}

cout << endl;

}



return 0;

}


1 Expert Answer

By:

Patrick B. answered • 05/17/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.