Program in Javascript to find the sum of N Natural Numbers - using Loop

Posted by Rajnilari2015 under JavaScript category on | Points: 40 | Views : 2862
The below function will help us to find the sum of N Natural numbers using loop

function SumofNNaturalNumbers() {

var N=10;
var sum = 0;
var numbers = [];
var count = 1;

while ( count <= N+1 ) numbers.push( count++ );
for(var number in numbers) { sum += parseInt(number);}
alert("Sum Of N Natural Numbers : " + sum);

We are looping through the numbers and taking a count variable and pushing the individual numbers to the numbers array. Then we have applied the loop of javascript and summing the individual numbers. Finally, printing the same using the alert.

Comments or Responses

Login to post response