Swapping numbers in a multidimensional array

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 replies · 4K views
magnifik
Messages
350
Reaction score
0
i'm trying to swap the 43 and the 435, but instead 435 is printed where 43 should be.

Code:
#include <iostream>
using namespace std;

void print(const int matrix[][2]);
void swap(int matrix[][2]);

int main(){
	int matrix[2][2] = {{14, 435}, {43, 65}};

	print(matrix);
	cout << endl;
	swap(matrix);
}

void print(const int matrix[][2]){
	for (int i = 0; i < 2; i++){
		for (int j = 0; j < 2; j++){
			cout << matrix[i][j] << " ";
		}
		cout << endl;
	}
}

void swap(int matrix[][2]){
	for (int r = 0; r < 2; r++){
		for (int c = 0; c < 2; c++){
			int temp = matrix[r][c];
			matrix[r][c] = matrix[c][r];
			matrix[c][r]= temp;
			cout << matrix[c][r] << " ";
		}
		cout << endl;
	}
}
 
on Phys.org
The problem is that your swap function is swapping each element in your matrix twice, which is the same as not swapping anything at all.

When r = 0 and c = 1, 435 is swapped for 43 and vice versa. But when r = 1 and c = 0, the 435 and 43 are swapped again. What you need to do is cycle through the matrix entries above the main diagonal or below the main diagonal (one or the other). So for this problem all you need to do is swap the entry at matrix[0][1] and you're done.

It's probably easier to see if you have a larger matrix, say 3 x 3. If you work on the entries below the main diagonal, you want to work on the entries at matrix[1][0], matrix[2][0], and matrix[2][1]. You'll need to figure out how to have your two loops do this.