# C++ Program to Find the Sum of Natural Numbers using Recursion

22/05/2024

To Create a C++ program that calculates the sum of natural numbers using recursion, you will need to define a recursive function that continues to sum numbers until it reaches the base case. Recursion is a powerful technique in programming where a function calls itself to solve a smaller version of a larger problem.

Here’s a step-by-step implementation of how you might write this C++ program:

C++ Code:

#include <iostream>

using namespace std;

// Recursive function to calculate the sum of natural numbers

int sumOfNaturalNumbers(int n) {

if (n <= 0) {

return 0; // Base case: if n is 0 or negative, return 0

} else {

return n + sumOfNaturalNumbers(n – 1); // Recursive case

}

}

int main() {

int n;

// Asking user for the number of natural numbers to sum

cout << “Enter a positive integer: “;

cin >> n;

// Handling input errors

if (n < 0) {

cout << “Please enter a positive integer.” << endl;

} else {

// Calculating the sum using recursion

int result = sumOfNaturalNumbers(n);

cout << “The sum of the first ” << n << ” natural numbers is ” << result << “.” << endl;

}

return 0;

}

Explanation:

1. Recursive Function (sumOfNaturalNumbers):
• This function takes an integer n as its argument.
• The base case is defined for when n is less than or equal to 0. In such cases, the function returns 0 because the sum of zero numbers is zero.
• The recursive case involves calling the function itself with n-1 and adding n to the result of that recursive call. This effectively sums all numbers from n down to 1.
2. Main Function:
• The main function prompts the user to enter a positive integer. It checks if the input is a positive integer before proceeding.
• It calls the sumOfNaturalNumbers function and outputs the result, which is the sum of the first n natural numbers.

Sample Output:

If a user inputs 10, the output would be:

Enter a positive integer: 10

The sum of the first 10 natural numbers is 55.

This program clearly illustrates how recursion can be used to sum up natural numbers efficiently without the need for loops or other iterative constructs. This approach is particularly useful for understanding recursion and its practical applications in solving mathematical problems.