Tuesday, April 15, 2008

A Number's Spiral.... in C

Hello again,

Recently, I had my Computer Programming online test... For that I was practising coding in C.. I am giving one of my program code.. which will display numbers in a spiral fashion...

For example, if you give input as 5 then the output would be:
01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09

Hope, you will find it interesting...


//This spiral program is made by Neeraj Agarwal.
#include

int main()
{
int i, j, k, l, m, n, o, p, q, r, s, sq;
int f[20000];
char fl;
printf("Enter a number : ");
scanf("%d",&n);
sq = n * n;
for(j=1;j<=sq;j++)
f[j] = 0;
i=1;
fl = 'f';
l = 1;
while(l<=sq)
{
if(fl == 'f')
{
f[i] = l;
i = i + 1;

if(f[i]!=0 || (i-1)%n == 0)
{
i = i - 1 + n;
fl = 'd';
}
l++;
}
else if(fl == 'b')
{
f[i] = l;
i = i - 1;
if(f[i] != 0 || (i+1)%n==0)
{
fl = 'u';
i = i + 1 - n;
}
l++;
}
else if(fl == 'u')
{
f[i] = l;
i = i - n;
if(f[i] != 0 || i%n==0)
{

fl = 'f';
i = i + n + 1;
}
l++;
}
else if(fl == 'd')
{
f[i] = l;
i = i + n;
if((f[i] != 0 || i>sq))
{
fl = 'b';
i = i - n -1;
}
l++;
}
}
for(j=1; j<=sq; j++)
{
if((j-1)%n==0)
printf("\n");
if(f[j]<=9)
{
printf("0%d ",f[j]);
}
else
printf("%d ",f[j]);
}
return 0;
}



Byee...

1 comment:

Unknown said...

hey nice post dear..
Should be helpful to a lot of people.. Its a famous interview question.. A good to take excercise.