C/C++ program for calling main() in main()

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 1

Input: N = 5
Output: 5 4 3 2 1

Approach:



  1. Use static variable to initialise the given number N.
  2. Print the number N and decrement it.
  3. Call the main() function recusrsively after above step.

Below is the implementation of the above approach:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
    }
}

chevron_right


C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
    }
}

chevron_right


Output:

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.




My Personal Notes arrow_drop_up


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.