C++ for Beginners: C++ program to Find Sum of Natural Numbers using Recursion

Hits: 9

(C++ programming Example for Beginners)

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

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


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<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.

 

 

C++ for Beginners: C++ program to Find Sum of Natural Numbers using Recursion

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.