say you have a 4x4 two dimensional array,
write a function that rotates it 90 degrees
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
Becomes:
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
This is working code in C, which accepts the size
of square matrix and matrix elements and prints
the rotated matrix.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int s, **arr, **arr2;
int i, j, c, r;
printf("\n Enter the size of square matrix : ");
scanf("%d",&s);
arr=(int *)malloc(s*sizeof(int));
arr2=(int *)malloc(s*sizeof(int));
printf("\n Enter the array elements :");
for(i=0;i<s;i++)
{
arr[i]=(int *)malloc(s*sizeof(int));
arr2[i]=(int *)malloc(s*sizeof(int));
}
for(i=0;i<s;i++)
{
printf("\n Enter the %d the row : ", i);
for(j=0;j<s;j++)
{
c=s-1-i;
r=j;
scanf("%d",&arr[i][j]);
arr2[r][c]=arr[i][j];
}
}
for(i=0;i<s;i++)
{
printf("\n");
for(j=0;j<s;j++)
{
printf("%d ", arr2[i][j]);
}
}
}
No comments:
Post a Comment