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:
Your code should produce:
Hints:
- To swap two locations, you need to use a temp variable: temp = location1; location1 = location2; location2 = temp.
- You only should use the usual two loops - when you are on [i][j] it needs to swap with [j][i]
- 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:
- 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;
}