Given a number N, the task is to write C/C++ program to print the number from N to 1 by calling the main() function using recursion.
Examples:
Input: N = 10
Output: 10 9 8 7 6 5 4 3 2 1Input: N = 5
Output: 5 4 3 2 1
Approach:
- Use static variable to initialise the given number N.
- Print the number N and decrement it.
- Call the main() function recusrsively after above step.
Below is the implementation of the above approach:
C
// C program to illustrate calling // main() function in main() itself #include "stdio.h" // Driver Code int main() { // Declare a static variable static int N = 10; // Condition for calling main() // recursively if (N > 0) { printf("%d ", N); N--; main(); } } |
C++
// C++ program to illustrate calling // main() function in main() itself #include "iostream" using namespace std; // Driver Code int main() { // Declare a static variable static int N = 10; // Condition for calling main() // recursively untill N is 0 if (N > 0) { cout << N << ' '; N--; main(); } } |
10 9 8 7 6 5 4 3 2 1
Time Complexity: O(N), where N is the given number.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Is it fine to write "void main()" or "main()" in C/C++?
- Difference between "int main()" and "int main(void)" in C/C++?
- Calling virtual methods in constructor/destructor in C++
- C/C++ program to print Hello World without using main() and semicolon
- return statement vs exit() in main()
- Functions that are executed before and after main() in C
- How to print "GeeksforGeeks" with empty main() in C, C++ and Java?
- How to change the output of printf() in main() ?
- Can main() be overloaded in C++?
- How to write a running C code without main()?
- Executing main() in C/C++ - behind the scene
- Print "Hello World" with empty or blank main in C++
- What does main() return in C and C++?
- How to call some function before main() function in C++?
- How can we write main as a class in C++?
- C program to detect tokens in a C program
- C program to print a string without any quote (singe or double) in the program
- C Program for Program to find area of a circle
- C Program for Program for array rotation
- Lex Program to remove comments from C program
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

