Ron Axm
Ron Axm

Reputation: 101

Is this logical approach right for my program?

Program - Rotating matrix 90 degrees clockwise. I am a beginner in coding. I came across this question on GeeksforGeeks. I found the solutions very complex so tried applying my logic. But I don't know if my logic is appropriate for the program. Kindly guide me.

#include<stdio.h>
int main()
{
    int  A = 0 , a = 0 , b = 0;
    int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    printf("90 Degree rotation: \n");
    printf("\n");
    for(A = 2; A >= 0; A--)
    {
        for(a = 0; a < 3 ; a++)
        {
            for(b = 0; b < 3 ; b++)
            {
                if(b==A)
                    printf("%d\t",arr[a][b]);
            }
        }
        printf("\n");
    }
}

Input

1 2 3
4 5 6
7 8 9

Output

3 6 9
2 5 8
1 4 7

Upvotes: 1

Views: 62

Answers (1)

Bromind
Bromind

Reputation: 1138

This is you matrix, with the axis you chose :

  b ->
a 1 2 3
| 4 5 6
V 7 8 9

That is, for a fixed a for instance, if you increase b, you print "the next number" (provided b is not 2). Similarly, if you increase a with the same b, you take the same column, but the next line.

So, you can have the following pseudo program, to print a full column (on a line):

print_column(b):
  for a from 0 to 2
    print arr[a][b]
  print newline

What do you want ? You want to print the following :

3 6 9
2 5 8
1 4 7

That is printing the last column, then the middle one, then the first one, which is done by the following pseudo-program:

print the 3rd column of arr
print the 2nd column of arr
print the 1st column of arr

or, more concisely :

for b from 2 to 0
  print the b-th column of arr.

So, the final pseudo code is (inlining the print_column procedure):

for b from 2 to 0
  for a from 0 to 2
    print arr[a][b]
  print newline

Or, in C:

for(b = 2; b >= 0 ; b--)
{
    for(a = 0; a < 3 ; a++)
    {
            printf("%d\t",arr[a][b]);
    }
    printf("\n");
}

Upvotes: 1

Related Questions