fastread homefastrread library fastread menu

C++ : Find Sum of Natural Numbers using Recursion

Tutorial by:Manisha Dubey      Date: 2016-06-18 04:32:11

❰ Previous Next ❱

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

❰ Previous Next ❱


C++

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website