C++ Program to find the sum of n natural numbers by using a recursive function

Here in this program, the sum of natural numbers is calculated by using a recursive function.

How can we calculate the sum of n natural numbers?

Natural numbers are numbers that include all the whole numbers excluding the number 0.
Natural numbers = { 1, 2, 3, 4, 5…………………..}
Here n is the number of natural numbers. So to find the sum of n natural numbers we have to add 1 + 2 + 3 + …….+ n.
For example:  n = 6
sum = 1 + 2 + 3 + 4 + 5 + 6 = 21

Recursion in C++

A function that calls itself is known as a recursive function. And, this technique is known as recursion.
The recursion continues until some condition is met.
To prevent infinite recursion, the if...else statement (or similar approach) can be used where one branch makes the recursive call and the other doesn't.

Working on Recursion in C++

void recurse()
{
    ... .. ...
    recurse();
    ... .. ...
}

int main()
{
    ... .. ...
    recurse();
    ... .. ...
}

C++ program to find the sum of n natural numbers by using a recursive function

Here the program takes a positive integer from the user and calculates the sum up to the given number.
Ask the user to enter a positive integer and read the value to the variable n. Define a recursive function function add().  Pass the variable n to the function add().
Int add(int n)
Check the condition n != 0 in an if condition statement.
If(n != 0)
Add n to the addition result of n-1.
return n + add(n – 1);
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.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Define a function add();
    n + add ( n- 1) until n != 0;
    return the value  

Step 4: Open the integer type main function; int main().

Step 5: Declare integer variables; n;

Step 6: Print a message to enter a positive integer.

Step 7: Read the value into the variable n;

Step 8: Call the function add(n);

Step 9: Exit;
 

C++ Source Code

                                          #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 a positive integer: 12
Sum =  78