Saturday, June 13, 2026
HomeLanguagesJavascriptJavaScript Program to Find Sum of Natural Numbers using Recursion

JavaScript Program to Find Sum of Natural Numbers using Recursion

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




// Javascript program to find the sum of 
// first n natural numbers
function findSum(n) {
    if (n !== 0)
        return n + findSum(n - 1);
    else
        return n;
}
  
// Driver code
const n = 5;
console.log(findSum(n));


Output

15

Example 2: In this example, we will calculate and output the sum of the first 10 natural numbers.

Javascript




// Javascript program to find the sum of 
// first n natural numbers
function findSum(n) {
    if (n !== 0)
        return n + findSum(n - 1);
    else
        return n;
}
  
// Driver code
const n = 10;
console.log(findSum(n));


Output

55

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS