Sum of Natural Numbers

Sum of First N Natural Numbers Using Recursion

A natural number is any whole number above 0.

This program is supposed to output the sum of the first N natural numbers.

Use recursive calling with sumOfNaturalNumbers to find the sum of the first N natural numbers.

#include <iostream>

// Your function declaration here

int main() 
{
    int N;
    std::cout << "Enter the value of N: ";
    std::cin >> N;

    int result = sumOfNaturalNumbers(N);
    std::cout << "The sum of the first " << N << " natural numbers is: " << result << "\n";
}

Hint

A recursive function generally has a base case. For this problem, when N is 1, the sum is simply 1. For all other values of N, the sum can be found by adding N to the sum of the first N-1 natural numbers.

Answer

#include <iostream>

int sumOfNaturalNumbers(int N)
{
    if (N == 1)
        return 1;  // Base case
    else
        return N + sumOfNaturalNumbers(N - 1);  // Recursive call
}

int main() 
{
    int N;
    std::cout << "Enter the value of N: ";
    std::cin >> N;

    int result = sumOfNaturalNumbers(N);
    std::cout << "The sum of the first " << N << " natural numbers is: " << result << "\n";
}

Note that this function assumes that you input a positive value as N. If you give a negative value sumOfNaturalNumbers will keep subtracting 1 from it without it even becoming 1. This creates an unintentional infinite loop.Re-write this recursive function as a function with a while loop.

To fix this you can include a check for N>0 before getting the result. Alternatively you can check if if (N<=1) return 1; inside sumOfNaturalNumbers.

Questions