Find the sum of first n natural numbers in JavaScript
In this tutorial, you are 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.
Programs
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}`);