Natural numbers include all positive integers from 1 to infinity. It does not include zero (0). Given a number n, find the sum of the first n natural numbers. To calculate the sum, we will use the recursive function recur_sum().
Examples:
Input: 3
Output: 6
Explanation: 1 + 2 + 3 = 6Input: 5
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15
The Sum of Natural Numbers Using Recursion
Below is a C++ program to find the sum of natural numbers up to n using recursion:
C++
// C++ program to find the sum // of natural numbers up to n // using recursion #include <iostream> using namespace std;
// Returns sum of first // n natural numbers int recurSum( int n)
{ if (n <= 1)
return n;
return n + recurSum(n - 1);
} // Driver code int main()
{ int n = 5;
cout << recurSum(n);
return 0;
} |
Output
15