In this example, we will learn to write a program that finds the sum of natural numbers in JavaScript.
The positive integers like 1,2,3---n are called natural numbers
Step 1: we use for loop and add i to sum at each iteration.
finally we print sum
PROGRAM :
// Program to find sum of natural number
// sum upto n terms
let n=100;
let sum=0;
for(let i=1;i<=n;i++){
sum+=i
}
console.log('The sum of ',n,'natural numbers:', sum)
OUTPUT :
Complexity
Time Complexity : O(N)
Space Complexity : O(1)
Space Complexity : O(1)