1

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?

2
  • 3
    You seem to have a grasp of variable initialization/incrementing, so presumably you just need to know the syntax for for? MDN provides all the documentation you need: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 9, 2014 at 12:14
  • 1
    Have a go and you'll probably get it about right. Commented Jan 9, 2014 at 12:15

3 Answers 3

3
var total = 0;

for (var i = 1; i <=10; i ++){
     total += i;
}
console.log(total);
Sign up to request clarification or add additional context in comments.

4 Comments

i think you mean i<=10, because OP want find the sum of the first 10 natural numbers
@Grundy doesnt 10 need to be in that calculation? 'i<=10' wont add 10 to the end.
1..9 is nine numbers, but OP want ten, also check result of code OP and in your sample :-)
since this is a pre-test loop you will get 10 because the loop runs until it is greater that 10. This will run through the 1-9 then on iteration 10, it bumps the count up to 11 and then when the loop returns to the top it fails the test.
2

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.

Comments

1

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

1 Comment

A yet-ception. THanks Grundy :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.