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


January 21, 2023, Learn eTutorial
1484

In this C++ 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 without Zero. for eg, the natural numbers = { 1, 2, 3, ……..}. here n is the user input that 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, if n = 6, then sum = 1 + 2 + 3 + 4 + 5 + 6 = 21

Recursion in C++

A function is called a recursive function if that function calls itself continuously until some conditions are met. 

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

In this program, we ask the user to enter a positive integer and read the value to the variable n. Define a recursive function add().  Pass the variable n to the function add() Check the condition n != 0 in an if conditional statement. 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). in the next function call, 9 is added with 8 (9 - 1 = 8). This goes on until the number reaches 0 when the function returns 0. Finally, we get the result of 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