Oracle
Oracle

Reputation: 25

Reversing a 2D array in C

I can't seem to create a general method that will reverse a 2D array of any size. I have the following code, which only works for a 3x3 array. Is there a way to modify this code to reverse any size 2D array?

I need my array to go from:
[ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]

to:  
[ 3 2 1 ]
[ 6 5 4 ]
[ 9 8 7 ]

But this should work for any array size, not just 3x3 and not just an nxn array (square array).

    #include<stdio.h>
#include<string.h>

int main()
{
    int r,r2,c,c2,temp;

    int rows = 3;
    int columns = 3;

    int a[rows][columns]; 

    a[0][0] = 1;
    a[0][1] = 2;
    a[0][2] = 3;

    a[1][0] = 4;
    a[1][1] = 5;
    a[1][2] = 6;

    a[2][0] = 7;
    a[2][1] = 8;
    a[2][2] = 9;

    r = 0;
    r2 = rows-1;

    c = 0;
    c2 = columns-1; 

    while(r<=r2){
        while(c<=c2){
            temp = a[r][c];
            a[r][c] = a[r2][c2];
            a[r2][c2] = temp;

            c++;
            c2--;
        }

        temp = a[r][c];
        a[r][c] = a[r2][c2];
        a[r2][c2] = temp;

        r++;
        r2--;

    }


    for(r=0;r<3;r++){
        for(c=0;c<3;c++){
            printf("%d\n",a[r][c]);
        }
    }
}

Upvotes: 2

Views: 11448

Answers (1)

user2736738
user2736738

Reputation: 30926

You are reversing each row of the array. So write a function that will reverse an array passed as an parameter to it.

The second one would be something like,

void swap(int *a, int *b){
     int temp = *a;
     *a = *b;
     *b = temp;
}
void rev(int a[],const int col){
    for(size_t i = 0; i < col/2; i++){
        swap(&a[i],&a[col-i-1]);
    }
}

int main(void){
...

for(size_t i = 0;  i < rows; i++)
   rev(a[i],columns);
...
return 0;
}

The problem with your code is that you yourself are contradicting what you want to achieve.

First swap you made is between r2,c2 and 0,0 This way at first iteration inside the while you are swapping last row and first row. That is what you didn't want to do (atleast the question says so).

Upvotes: 1

Related Questions