Friday, February 6, 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

Most Popular

Dominic
32490 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6862 POSTS0 COMMENTS
Nicole Veronica
11985 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12073 POSTS0 COMMENTS
Shaida Kate Naidoo
6995 POSTS0 COMMENTS
Ted Musemwa
7236 POSTS0 COMMENTS
Thapelo Manthata
6946 POSTS0 COMMENTS
Umr Jansen
6931 POSTS0 COMMENTS