C++ Program For Sum of Natural Numbers Using Recursion
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 = 6
Input: 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++
#include <iostream>
using namespace std;
int recurSum( int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
int main()
{
int n = 5;
cout << recurSum(n);
return 0;
}
|
Last Updated :
23 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...