Skip to content
Home » Blog » C++ Program to Find Sum of Natural Numbers using Recursion

C++ Program to Find Sum of Natural Numbers using Recursion

Natural Numbers using Recursion

In this Program, you’ll learn to find the sum of Natural Numbers using Recursion function.

To nicely understand this example to find Natural Numbers using Recursion, you should have the knowledge of following C++ programming topics:

  1.  Recursion
  2. if, if…else and Nested if…else
  3. Functions
  4. User-defined Functions

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

Program to Calculate Sum of Natural numbers using Recursion

#include<iostream>
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.

If you have any doubts about C++ Program to find Natural Numbers using Recursion do comment. Documentation