gelolopez
gelolopez

Reputation: 174

Writing a javascript to find sum of a series using for loop

I am having a problem in writing a javascript for finding the sum of the first 10 natural numbers. I have written the code with a while function and it is working well:

var total = 0, count = 1;
while (count <= 10) {
    total += count;
    count += 1;
}
console.log(total);

I am now wondering how you can do this using a for loop, if it is possible. Any help?

Upvotes: 1

Views: 8646

Answers (3)

Grundy
Grundy

Reputation: 13381

Yet another variant based on lukas.pukenis answer

Array.apply(null,Array(10)) // [undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]
     .map(function(_, index){
              return index+1;
          }) // [1,2,3,4,5,6,7,8,9,10]
     .reduce(function(total,curr){
                 return total+curr
             }); // 55

Upvotes: 1

lukas.pukenis
lukas.pukenis

Reputation: 13597

An alternative for loops in this case is - reduce.

Arrays have reduce method which usage looks like this:

[1,2,3,4].reduce(function(total, number) {
  return total + number;
}, 0);

You pass in a function accepting a total and current number from array and return their sum.

Zero at the end is starting value.

Arrays also have forEach method which you can use to iterate through your array like this:

var sum = 0;
[1,2,3,4].forEach(function(number) {
  sum += number;
});

PS: reduce in some languages has an alias - fold.

Upvotes: 2

SaggingRufus
SaggingRufus

Reputation: 1834

var total = 0;

for (var i = 1; i <=10; i ++){
     total += i;
}
console.log(total);

Upvotes: 3

Related Questions