Wednesday, September 21, 2011

Well today somebody asked me this question
Write a C function that will print 1 to N one per each line on the stdout where N is a int parameter to the function. The function should not use while, for, do-while loops, goto statement, recursion, and switch statement.

Was able to do it.. therefore thought of sharing it too..

#include <setjmp.h>
#include <stdio.h>

void myfunc(int n)
{
 jmp_buf ebuf;
 int i;
 int k = 1 ;
 i = setjmp(ebuf);
 if(i == 0)
 {
  longjmp(ebuf, k++);
 }
 else
 {
  if ( i <= n )
  {
   printf("%d\n", i);
   longjmp(ebuf, k++);
  }
 }
}