Thursday, April 17, 2008

Numbers spiral in a triangular pattern...

Hello again...

After showing you my number's spiral in a rectangular pattern, now I would like to show you in a triangular pattern. For ex, if your input is 4, then the output pattern would be:

01
12 13 02
11 16 15 14 03
10 09 08 07 06 05 04

Hope you will find the code interesting...

#include
int main()
{
int i, i2, j, k, l=1, m, n, o, p, q, r, s, sq, f[20][20];
char fl='f';
printf("Enter a number : ");
scanf("%d",&n);
sq = n * n;

for(j=1;j<=n;j++)
{
for(i=1;i<=((2*n) - 1);i++)
f[j][i] = 0;
}
i = n;
i2 = 1;
while(l<=sq)
{
if(fl == 'f')
{
f[i2][i] = l;
i2++;
i++;

if(f[i2][i]!=0 || i2>n)
{
i2 = i2 - 1;
i = i - 1 - 1;
fl = 'b';
}
l++;
}
else if(fl == 'b')
{
f[i2][i] = l;
i2 = i2;
i = i - 1;
if(f[i2][i] != 0 || i<=0)
{
fl = 'u';
i2--;
i = i + 1 + 1;
}
l++;
}
else if(fl == 'u')
{
f[i2][i] = l;
i2--;
i = i + 1;
if(f[i2][i] != 0)
{
fl = 'f';
i2 = i2 + 1;
i = i -1 + 1;
}
l++;
}
}
int z = 0, tt=1, kl;
for(j=1; j<=n; j++)
{
for(kl=1;kl<=((2*n) - 1);kl++){
if(f[j][kl] != 0)
{
if(f[j][kl] <10)
printf("0%d ",f[j][kl]);
else
printf("%d ",f[j][kl]);

}
else
printf(" ");
}

printf("\n\n");

}
return 0;
}




Byeee

1 comment:

RaSh said...

C++ Codes... humm thats something new!! :)

BTW just a suggestion... next time u post a code, do add comments (edit html and add title attribute if you prefer...) :D

Keep Posting!!