Matrix Rotation Clockwise
In this c program we are going to see how to rotate the matrix in clockwise direction by 90 degrees.
Solution
#include<stdio.h> //Header file
#include<stdlib.h>//Header file
int main()
{
int n,i,j,x,r=0;
scanf("%d",&n);//getting input n value for input matrix rotation
int a[n][n];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
scanf("\n");
}
scanf("%d",&x); //Getting Rotation angle of matrix
if(x%90==0) //Check for angle multiples of 90 degree matrix rotation
{
if(x==0)
r=0; //if x==0 the r==0 because matrix rotation will be same as input matrix.
else
{
r=x/90; // determining the r value based on given angle by dividing 90
r=r%4; //determining again r value because matrix rotation are of four types(90,180,270,360) only.
}
}
else
{
printf("Invalid Matrix");// if it is not multiples of 90 degree angle then it prints invalid matrix and exit the program
exit(0);
}
if(r==1) // for 90 degree matrix rotation
{
for(i=0;i<n;i++,printf("\n"))
{
for(j=n-1;j>=0;j--)
{
printf("%d ",a[j][i]);
}
}
}
else if(r==2) // for 180 degree matrix rotation
{
for(i=n-1;i>=0;i--,printf("\n"))
{
for(j=n-1;j>=0;j--)
{
printf("%d ",a[i][j]);
}
}
}
else if(r==3) // for 270 degree matrix rotation
{
for(i=n-1;i>=0;i--,printf("\n"))
{
for(j=0;j<n;j++)
{
printf("%d ",a[j][i]);
}
}
}
else // for 360 degree matrix rotation
{
for(i=0;i<n;i++,printf("\n"))
{
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
}
}
return 0;
}
Input 1
3
1 2 3
4 5 6
7 8 9
45
Output 1
Invalid Matrix.
Input 2
3
1 2 3
4 5 6
7 8 9
90
Output 2
Matrix Rotation 90 degree
7 4 1
8 5 2
9 6 3