Find the Sum of Natural Numbers in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to find the sum of natural numbers in JavaScript. The Positive Integers known as Natural Numbers. In JavaScript, we can use either for loop or while loop to find the sum of n natural numbers.

Syntax

sum(n) = 1+ 2 + 3 + ... + n

Example 1: Sum of n Natural Numbers using for loop

// program to find the sum of natural numbers

function FindSum(n){
  let sum = 0;

    for (let i = 1; i <= n; i++) {
        sum =sum + i;
    }  
    return sum;
}

console.log(FindSum(5))

Output

15
55

Example 2 : Sum of n Natural Numbers using while loop

// program to display the sum of natural numbers

function FindSum(n){
    let sum = 0, i = 1;

    while(i <= n) {
        sum = sum + i;
        i++;
    }
    return sum;
}

console.log(FindSum(5));
console.log(FindSum(10));

Output

15
55