The sum of the first n natural numbers can be calculated by recursively adding each number from n down to 1. This approach demonstrates how a recursive function breaks a problem into smaller subproblems.
- The base case stops recursion when n becomes 1 or 0.
- Each recursive call adds the current value of n to the sum of the remaining natural numbers.
Illustration
For n = 5, the recursive calls work as follows:
recurSum(5)
= 5 + recurSum(4)
= 5 + 4 + recurSum(3)
= 5 + 4 + 3 + recurSum(2)
= 5 + 4 + 3 + 2 + recurSum(1)
= 5 + 4 + 3 + 2 + 1
= 15
-660.png)
Approach
- Define a recursive function recurSum(n) to calculate the sum.
- Return n when n <= 1 to stop the recursion.
- Otherwise, return n + recurSum(n - 1).
#include <iostream>
using namespace std;
// Returns the sum of the first n natural numbers
int recurSum(int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
int main()
{
int n = 5;
cout << recurSum(n);
return 0;
}
Output
15
Explanation: For n = 5, the function keeps calling itself with n - 1 until it reaches the base case. The returned values are then added while the recursive calls complete, producing 1 + 2 + 3 + 4 + 5 = 15.