Suppose, we have a 2D array and we have to print that matrix in spiral form.For example:-
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Program in C:
#include <stdio.h>
#define MAX 5
int main()
{
int a[MAX][MAX],i,j,k,l,row,col;
printf("enter the number of rows and column=");
scanf("%d %d",&row,&col);
printf("Enter element:\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
k=0;
l=0;
while(k<row && l<col)
{
for(i=l;i<col;i++)
{
printf("%d ",a[k][i]);
}
k++;
for(i=k;i<row;i++)
{
printf("%d ",a[i][col-1]);
}
col--;
if(k<row)
{
for(i=col-1;i>=l;i--)
{
printf("%d ",a[row-1][i]);
}
row--;
}
if(l<col)
{
for(i=row-1;i>=k;i--)
{
printf("%d ",a[i][l]);
}
l++;
}
}
return 0;
}
INPUT:
1 2 3 4
5 6 7 8
9 10 11 12
1314 15 16
OUTPUT:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
No comments:
Post a Comment