+ 2

While loop

Why does the answer evaluate to 15? Shouldn't the answer be 5? var sumOfNumbers = 0; var number of loops =5; var counter =1; while (counter <= numberOfLoops) { sumOfNumbers += counter; counter++; } alert (sumOfNumbers);

11th Apr 2018, 12:56 AM
Tim Millar
Tim Millar - avatar
2 Answers
+ 4
It’s not 5 because you increase the counter by one each time so sumOfNumbers is 1+2+3+4+5 which is 15
11th Apr 2018, 1:12 AM
TurtleShell
TurtleShell - avatar
+ 2
In every loop counter is added to sumOfNunbers and being incremented results as sumOfNumbers = 1+2+3+4+5 = 15
11th Apr 2018, 1:13 AM
kaliki chandu
kaliki chandu - avatar