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

To find the sum of natural numbers using recursion, we need to understand the concept of recursion and how to apply it in C++ programming.

Recursion is a programming technique where a function calls itself to solve a problem.

In this case, we can write a function that calls itself repeatedly until a base condition is met, and the sum of natural numbers is calculated.

Let’s take a look at the C++ program to find the sum of natural numbers using recursion:

#include <iostream>

using namespace std;

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

int main()
{
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << "Sum of natural numbers from 1 to " << n << " is " << sum(n);
    return 0;
}

The above program takes an input of a positive integer and calculates the sum of natural numbers from 1 to the entered number.

The sum function takes an integer n as input and uses recursion to calculate the sum of natural numbers.

In the sum function, we first check if n is equal to 0. If it is, then we have reached the base condition, and the function returns 0.

If n is not equal to 0, then we add n to the sum of natural numbers from 1 to n-1 (which is calculated by calling the sum function recursively with n-1 as the argument).

In the main function, we take an input of a positive integer n and call the sum function to calculate the sum of natural numbers from 1 to n. The result is then displayed on the screen.

In conclusion, the above C++ program is a simple and effective way to calculate the sum of natural numbers using recursion.

It can be used in various scenarios, such as in mathematical and scientific calculations.

Understanding recursion and its application in programming can help to solve complex problems efficiently and effectively.