Tuesday, 9 August 2011

Spiral of a Matrix.

The Following code prints the matrix in a spiral manner.


Program Code:



#include<conio.h>
#include<stdio.h>
void main()
{
int m,n,i,j,left,right,top,down,len,itr;
int a[5][5];
clrscr();
printf ("enter m (max 5):  ");
scanf("%d",&m);
printf ("enter n (max 5):  ");
scanf("%d",&n);
printf ("Enter the elements of matrix one by one\n");
for (i=0;i<m;i++)
    for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf ("you have entered the matrix\n");
for (i=0;i<m;i++)
{   for (j=0;j<n;j++)
printf("%6d ",a[i][j]);
    printf ("\n");
}
left=0;
right=n;
top=0;
down=m;
itr=0;
len=m*n;
printf ("\n");
printf ("The spiral form is : ");
printf ("\n");
while (itr<len)
{
for (j=left;j<right;j++,itr++)
printf ("%d ",a[top][j]);
top++;


for (i=top;i<down;i++,itr++)
printf ("%d ",a[i][right-1]);
right--;


for (j=right-1;j>=left;j--,itr++)
printf ("%d ",a[down-1][j]);
down--;


for (i=down-1;i>=top;i--,itr++)
printf ("%d ",a[i][left]);
left++;
}
printf ("\n");
getch();
}


No comments:

Post a Comment