1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Swapping numbers in a multidimensional array

  1. Jul 17, 2010 #1
    i'm trying to swap the 43 and the 435, but instead 435 is printed where 43 should be.

    Code (Text):

    #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}};

        cout << endl;

    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;
  2. jcsd
  3. Jul 17, 2010 #2


    Staff: Mentor

    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook