JavaScript Program to Find Sum of Natural Numbers using Recursion
Last Updated :
24 Aug, 2023
We are given a number N and the task is to find the sum of the first n natural numbers using recursion.
Approach to Find Sum of Natural Numbers using Recursion:
In this approach, we are using the function to get the sum of the first N natural numbers.
First, we declare a function findSum(n) and pass the number (n) till now sum is calculated. Then check if the number is not equal to zero then return the n + findSum(n-1) otherwise return the number n (the number n is the sum of natural numbers).
Example 1: In this example, we will calculate the sum of the first 5 natural numbers.
Javascript
function findSum(n) {
if (n !== 0)
return n + findSum(n - 1);
else
return n;
}
const n = 5;
console.log(findSum(n));
|
Example 2: In this example, we will calculate and output the sum of the first 10 natural numbers.
Javascript
function findSum(n) {
if (n !== 0)
return n + findSum(n - 1);
else
return n;
}
const n = 10;
console.log(findSum(n));
|
Share your thoughts in the comments
Please Login to comment...