SOURCE CODE:
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],T[4]; // a for original matrix and b to store intermediate result
int i,j,k,t,n,m,beg,end;
printf("Enter the size of the matrix:");
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
b[i][j]=a[i][j];
}
printf("\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf(" %2d ",b[i][j]);
printf("\n");
}
beg=0;end=n-1;
t=0; // t for number of square rotations
m=n;
while(t<(m/2))
{
T[0]=a[beg][beg]; // T is to store the values at corners
T[1]=a[beg][end];
T[2]=a[end][end];
T[3]=a[end][beg];
i=beg;j=beg+1;
for(k=0;k<n-2;k++) // 4 fors for 4 rotations
{
b[i][j+1]=a[i][j];
j++;
}
j=end;
i=beg+1;
for(k=0;k<n-2;k++)
{
b[i+1][j]=a[i][j];
i++;
}
i=end;
j=end-1;
for(k=0;k<n-2;k++)
{
b[i][j-1]=a[i][j];
j--;
}
i=end-1;
j=beg;
for(k=0;k<n-2;k++)
{
b[i-1][j]=a[i][j];
i--;
}
b[beg][beg+1]=T[0]; //adding corner elements at rotated positions
b[beg+1][end]=T[1];
b[end][end-1]=T[2];
b[end-1][beg]=T[3];
beg++; //moving to inner squares
end--;
n=n-2;
for(i=beg;i<n;i++)
for(j=beg;j<n;j++)
a[i][j]=b[i][j];
t++;
}
printf("\nAfter rotation:\n\n");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
printf(" %2d ",b[i][j]);
printf("\n");
}
}
OUTPUT:
Enter the size of the matrix:5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
After rotation:
6 1 2 3 4
11 12 7 8 5
16 17 13 9 10
21 18 19 14 15
22 23 24 25 20
--------------------------------