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

C++ProgrammingServer Side Programming

The natural numbers are the positive integers starting from 1.

The sequence of natural numbers is −

1, 2, 3, 4, 5, 6, 7, 8, 9, 10……

The program to find the sum of first n natural numbers using recursion is as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int sum(int n) {
   if(n == 0)
   return n;
   else
   return n + sum(n-1);
}
int main() {
   int n = 10;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n);
   return 0;
}

Output

Sum of first 10 natural numbers is 55

In the above program, the function sum() is a recursive function. If n is 0, it returns 0 as the sum of the first 0 natural numbers is 0. If n is more than 0, then sum recursively calls itself itself with the value n-1 and eventually returns the sum of n, n-1, n-2…...2,1. The code snippet that demonstrates this is as follows.

int sum(int n) {
   if(n == 0)
   return n;
   else
   return n + sum(n-1);
}

In the function main(), the sum of the first n natural numbers is displayed using cout. This can be seen as follows −

cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n);
raja
Published on 27-Sep-2018 13:03:30
Advertisements