0

can someone explain why this loop does not output "i" in order "0 2 4 6 8 10", but instead it outputs "0 2 6 12 20 30 42 56 72 90" ?

  let nmb = 0;
  for(let i=0; i<50; i+=2){
      nmb+=i;
        document.write(nmb + " ");
    }
2
  • "this loop does not output "i" in order" It doesn't ouput i at all. You are printing nmb which adds i to its previous value. Commented Nov 15, 2019 at 21:55
  • 1
    In any programming language loops work as expected. Commented Nov 15, 2019 at 21:57

4 Answers 4

1
 let nmb = 0;
 for(let i=0; i<50; i+=2){
     nmb+=2;
     document.write(nmb + " ");
 }

This should solve the problem. The thing is, in your current solution, you are adding i number to the sum. So you add i=2 to nmb, nmb = 2. Then you add i=4 to nmb, nmb = 6, then you add i=6, nmb = 12 etc... You want to add constant value which is 2, not i value.

Sign up to request clarification or add additional context in comments.

Comments

0

Your loop is already incrementing i by 2 which is the number you want to display, making the nmb variable unnecessary. So just write out i:

for(let i=0; i<50; i+=2){
    document.write(i + " ");
}

Comments

0

You are always adding i instead of 2 to your sum.

You could just print i directly

 for(let i=0; i<50; i+=2){
    document.write(i + " ");
 }

Comments

0

I wanted to do something with Array.from, but this was the closest I got

let x = [], r = 25, i = 0;
while (x.push(i += 2) < r);
console.log(x.join(","))

Comments

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.