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 –




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

C++ implementation –




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


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

Notify of