0

I am attempting to write code to rotate an array 90 degrees clockwise in c++:

#include <iostream>

int main() {
    int ary[4][4] = { {1,2,3,4},
                      {6,7,8,9},
                      {11,12,13,14},
                      {16,17,18,19} };

    int temp[4][4];
    int l = sizeof(ary) / sizeof(ary[0]);
    int w = sizeof(ary[0]) / sizeof(ary[0][0]);
    //int size = sizeof(ary)/sizeof(int);
    std::cout << "Length: " << l << std::endl;
    std::cout << "Width: " << w << std::endl;
    std::cout << "Original Ary: " << std::endl;
    
    //prints each element of a 2D ary
    for (int i = 0; i < l; i++) {
        //cout<<"entered i2 loop"<<endl;
        for (int j = 0; j < w; j++) {
            //cout<<"entered j2 loop"<<endl;
            std::cout << ary[i][j] << " ";
            //endl after last elem in row
            if (j == w - 1) {
                std::cout << std::endl;
            }
        }
    }
    std::cout << std::endl;
    
    //rotates array 90 CW
    for (int i = 0; i < (l - 1); i++) {
        for (int j = i; j < (w-i-1); j++) {
            //swaps elements in ary
            temp[i][j] = ary[i][j];
            ary[i][j] = ary[w - 1 - j][i];
            ary[w - 1 - j][i] = ary[l - 1 - i][w - 1 - j];
            ary[j][l - 1 - i] = temp[i][j];
        }
    }
    std::cout << "Rotated Ary: " << std::endl;
    
    //prints each element of a 2D ary
    for (int i = 0; i < l; i++) {
        //cout<<"entered i2 loop"<<endl;
        for (int j = 0; j < w; j++) {
            //cout<<"entered j2 loop"<<endl;
            std::cout << ary[i][j] << " ";
            //endl after last elem in row
            if (j == w - 1) {
                std::cout << std::endl;
            }
        }
    }
    return 0;
}

This is the current output:

Length: 4
Width: 4
Original Ary:
1 2 3 4
6 7 8 9
11 12 13 14
16 17 18 19

Rotated Ary:
16 11 6 1
17 12 7 2
18 13 13 3
19 17 18 19

I was expecting the rotated array to look like this:

16 11 6 1
17 12 7 2
18 13 8 3
19 14 9 4

As you can see, the first 2 lines rotate correctly but the values 13, 17, 18, and 19 repeated in the last 2 lines when they should not be. What changes do I need to make to this code, and why does this program not work as intended?

genpfault
  • 51,148
  • 11
  • 85
  • 139

0 Answers0