C / C++ FAQs & Programming Resources - ProkutFAQ : Print1toNwithoutLoop

HomePage Recent Changes Recently Commented Login/Register

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

This is is very easy to implement in C++ using a constructor and a static member to count the number of objects instantiated of that class as shown in the below code:

C++

     #include <iostream>
     
     class a{
          public:
               a(){std::cout<<++i<<std::endl;}
          private:
               static int i;
     };
     
     int a::i; //allocates memory for the static variable
     
     int main(){
          int n=0;
          std::cout<<"Enter the maximum number that you want to print: ";
          std::cin>>n;
          a* array=new a[n]; //this statement prints 1 to n because creating an array of n objects calls the default class constructor n times
          return 0;
     }

Note: This does use implicit loop when objects are created, but there aren't any explicit looping statements or recursion in the program.

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 <stdio.h>
#include <setjmp.h>

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.

References

Setjmp and longjump functions article on Wikipedia


CategoryPuzzles
 Comments [Hide comments/form]
it is possible to use recursion to print the numbers!!!!
-- tataelxsi.co.in (2007-04-10 06:41:38)
can u explain more about how the (setjmp(jmpbuf)>n) works
-- 203.123.165.130 (2007-07-05 15:30:38)
I've added a brief explanation for how setjump and longjmp is used for that program, for more information, please visit the reference link given.
-- SharathAV (2007-07-20 09:36:08)
For the C version, why not use goto which is easier to read than the setjmp/longjmp version?
-- 117.97.70.22 (2009-05-07 17:27:20)
Page was generated in 0.0993 seconds