Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Can Main Function Call Itself in C++?



The main() function can call itself in C++. This is an example of recursion, i.e., a function calling itself. In recursion, a function calls itself over and over again with modified arguments until it reaches its base case or the termination condition, where the recursion stops.

In this article, we will go through three C++ examples where the main function calls itself.

Counting Numbers up to N

To count numbers up to 'n', we will recursively call the main function until it reaches 'n'.

Example

The following example calls the main() function recursively to print the numbers from 1 to 10.

#include <iostream>
using namespace std;

int count = 1;

int main() {
    if (count <= 10) {
        cout << count << " ";
        count++;
        main();
    }
    return 0;
}

The output of the above code is as follows:

1 2 3 4 5 6 7 8 9 10

Counting Numbers from N to 1

This example demonstrates printing numbers backwards from 'n' to 1.

Example

In this example, the main() function calls itself recursively to print numbers starting from 10 to 1.

#include <iostream>
using namespace std;

int n = 10;

int main() {
    if (n > 0) {
        cout << n << " ";
        n--;
        main();
    }
    return 0;
}

The output of the above code is as follows:

10 9 8 7 6 5 4 3 2 1

Sum of First N Natural Numbers

To find the sum of the first 'n' natural numbers, we have used the recursion where the main() function calls itself recursively.

  • We have initialized the values of 'n' and 'sum' outside the main function.
  • We have used the if statement to check the termination condition of the recursive main() call.
  • Then we have stored the summation of 'n' and the value of 'sum' in the variable sum.
  • The value of the sum is then returned. It is the summation of the first 'n' natural numbers.

Example

In this example, we have calculated the sum of the first 10 natural numbers by recursively calling the main() function:

#include <iostream>
using namespace std;

int n = 10, sum = 0;

int main() {
    if (n > 0) {
        sum += n;
        n--;
        main();
    } else {
        cout << "Sum up to 10 natural numbers is: " << sum << endl;
    }
    return 0;
}

The output of the above code is as follows:

Sum up to 10 natural numbers is: 55
Updated on: 2025-05-13T19:34:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements