C++ Program to Find Sum of Natural Numbers using Recursion
In this example, we will learn a program to to find the sum of natural numbers by using a recursive function.
To understand this example, you should have the knowledge of the following C++ programming topics:
Sum of Natural Numbers using Recursion
The positive numbers 1, 2, 3... are known as natural numbers. The program below takes a positive integer from the user and calculates the sum up to the given number.
You can find the sum of natural numbers using loops as well. However, you will learn to solve this problem using recursion here
Example: Program to Calculate Sum of Natural numbers 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);
return 0;
}
Output 1
Enter an positive integer: 10 Sum = 55
Working
In this program, the number entered by the user is passed to the add()
function.
Suppose, 10 is entered by the user. Now, 10 is passed to the add()
function. This function adds 10 to the addition result of 9 (10 - 1 = 9). Next time, 9 is added to the addition result of 8 (9 - 1 = 8). This goes on until the number reaches 0, when the function returns 0.
Now, every function is returned to calculate the end result: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
Next Example
We hope that this Example helped you develop better understanding of the concept of "Sum of Natural Numbers using Recursion" in C++.
Keep Learning : )
In the next Example, we will learn about C++ Factorial of a Number Using Recursion
.