Tuesday, August 01, 2006

A simple Program

For any given input -'n', print the numbers from 1 to n and then from 'n-1' to 1 using only a single loop without any explicit if-else or ternary operator and not using any other memory other than the loop variable.

For Egs: If input is 4
OutPut : 1 2 3 4 3 2 1

1 comment:

bk said...

An approach using stack is:
#include
int fun(int);
void main()
{int n;
printf("enter ur no:\n");
scanf("%d",&n);
fun(n);
}
int fun(int n)
{ static int i=0,count=1;
i++;
printf("\t%d",i);
while(i<n&&count !=0)
{count++;
fun(n);
printf("\t%d",--count);
}
return 0;
}
There are other solutions also possible.