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