JavaScript Code

How to find the sum of first n natural numbers using JavaScript?


Problem Statement

given a positive integer n, write a JavaScript program to find the sum of first n natural numbers

Solution

to find the sum of first n natural numbers using JavaScript, we can either use the formula n(n + 1)/2, or iterate over a for loop from 1 to n and accumulate the sum

Program

1. sum of first n natural numbers using formula

n = 10;
sum = n * (n + 1) / 2;
console.log(`sum of first ${n} natural numbers = ${sum}`);

in the above program, we have used arithmetic multiplication, arithmetic addition, arithmetic division

2. sum of first n natural numbers using for loop

n = 10;
sum = 0;
for ( let i = 1; i <= n; i++) {
    sum += i;
}
console.log(`sum of first ${n} natural numbers = ${sum}`);