C/C++ program for calling main() in main()
Last Updated :
25 Oct, 2022
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:
- Use static variable to initialise the given number N.
- Print the number N and decrement it.
- Call the main() function recursively after above step.
Below is the implementation of the above approach:
C
#include "stdio.h"
int main()
{
static int N = 10;
if (N > 0) {
printf ( "%d " , N);
N--;
main();
}
}
|
C++
#include "iostream"
using namespace std;
int main()
{
static int N = 10;
if (N > 0) {
cout << N << ' ' ;
N--;
main();
}
}
|
Output:
10 9 8 7 6 5 4 3 2 1
Time Complexity: O(N), where N is the given number.
Share your thoughts in the comments
Please Login to comment...