Thursday, August 28, 2008

How to print 1 to n(a user defined value) without using any kind of loops or recursion ?

For C language, we can do this using setjmp and longjmp as given in the below code. Again there is an implicit loop, but no explicit looping construct or recursion used.

#include
#include

static jmp_buf jmpbuf;
static int val = 1, n;

void printvalue(void)
{
printf("%d\n",val++);
longjmp(jmpbuf,val);
}

int main()
{
printf("Enter the N value:");
scanf("%d",&n);
if (setjmp(jmpbuf) > n)
return 0;
else
printvalue();
}

Explanation

The first call to setjmp saves the current environment state in jmpbuf, and returns 0. So, if n is non-zero, the printvalue() is called. In printvalue function, the value of val is printed, and longjmp function is called, which returns the control back to main where the last setjmp was called. The setjmp macro on second and proceeding calls returns the val argument of longjump. This routine continues until the val becomes greater than n.

0 comments: