Example to find the sum of natural numbers by using a recursive function.

  • C++ Functions
  • Types of User-defined Functions in C++
  • C++ if, if…else and Nested if…else
  • C++ Recursion

The positive numbers 1, 2, 3… are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.

You can find the sum of natural numbers using loops as well. However, you will learn to solve this problem using recursion here

Example: Calculate Sum of Natural numbers using Recursion

#include 
using namespace std;

int add(int n);

int main()
{
    int n;

    cout << "Enter a positive integer: ";
    cin >> n;

    cout << "Sum =  " << add(n);

    return 0;
}

int add(int n)
{
    if(n != 0)
        return n + add(n - 1);
    return 0;
}

Output

Enter an positive integer: 10
Sum = 55

In this program, the number entered by the user is passed to the add() function.

Suppose, 10 is entered by the user. Now, 10 is passed to the add() function. This function adds 10 to the addition result of 9 (10 – 1 = 9).

Next time, 9 is added to the addition result of 8 (9 – 1 = 8). This goes on until the number reaches 0, when the function returns 0.

Now, every function is returned to calculate the end result: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.