Print all numbers between 1 to N without using any loop | 4 methods

Write a program to print all numbers between 1 to N without using loop.


 

Method 1: (Using static variable in recursive main)

We can call main() function recursively and with each call we print next element from the series. To store information about previous element printed, we use a static variable (Note that a global variable will also work fine).

 
C++ implementation –
 

OR

 
 

Method 2: (Using Recursion by implementing a separate method)

 
C++ implementation –
 

OR

 
 

Method 3: (Using C MACRO)

 
C++ implementation –
 

 
 

Method 4: (Without Recursion using struct/class with static field)

 
C++ implementation –
 

 
We can also use C++ class in place of struct.

 

 

 
Exercise: Extend method 3 to print numbers from 1 to 1000

 
References: http://stackoverflow.com/questions/4568645/printing-1-to-1000-without-loop-or-conditionals/

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
jhanak
Guest

How is the method 3 working?