Find Sum of Natural Numbers using Recursion with C++

04-11-17 Course- CPP

In this program, user is asked to enter a positive integer and sum of natural numbers up to that integer is displayed by this program. Suppose, user enters 5 then,


Sum will be equal to 1+2+3+4+5 = 15

Instead of using loops to find sum of natural numbers, recursion is used in this program.

Source Code to Calculated Sum 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);  /* recursive call */
}

 

Output


Enter an positive integer: 10
Sum = 55