Reputation: 49
I tried to code a right rotation for a 2D array.
Here is the main code:
for (int k = 0; k < rotate; k++) { //rotate is the no of times to shift right
for (int i = 0; i < n1; i++) { //n1 is no: of rows
for (int j = 0; j <n2; j++) { //n2 is no: of columns
//Shifting right
int temp = A[i][n2 - 1];
A[i][n2 - 1] = A[i][j + 1];
A[i][j + 1] = A[i][j];
A[i][j] = temp;
}
}
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
printf("%d", A[i][j]);
}
printf("\n");
}
It is working for size 2x2 where:
Input:
1 2
3 4
Output:
2 1
4 3
But it's not working for size 3x3 and above.
Input:
1 2 3
4 5 6
7 8 9
Output:
3 2 1
6 5 4
9 8 7
Where expected output is:
3 1 2
6 4 5
9 7 8
Please guide me about where I'm wrong and I apologize for any mistakes in my question.
Upvotes: 1
Views: 124
Reputation: 65
In your code you are referring to both left and right neighbours (though left one is wrongly referred because it should be last cell only for first interation) and don't keep value for next iteration.
It should be implemented as follows:
For each row left
is initalized with the value of very last item in the row, because it is on the left of 0th item. Then while iterating over row items we first save current value to temp
to use it later, then save left
to current item, and then use previosly saved temp
as new left
for next iteration.
for (int k = 0; k < rotate; k++) { //rotate is the no of times to shift right
for (int i = 0; i < n1; i++) { //n1 is no: of rows
int left = A[i][n2 - 1];
for (int j = 0; j < n2; j++) { //n2 is no: of columns
//Shifting right
int temp = A[i][j];
A[i][j] = left;
left = temp;
}
}
}
Upvotes: 1
Reputation: 21
See:
https://www.programiz.com/c-programming/examples/matrix-transpose ;)
You can change that solution to use one array.
Upvotes: 1