Why does the code outputs 124 instead of 125? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Why does the code outputs 124 instead of 125?

var a = 0; for (b=1; b<=5; b+=a) { document.write(b); a++; }

23rd Jun 2019, 1:02 AM
eMBee
eMBee - avatar
5 Answers
+ 9
a = 0 b = 1 b <= 5 ? => true Begin loop: write b <= 1 a = a + 1 <= 1 b = b + a <= 2 b <= 5 ? => true Iter loop: write b <= 2 a = a + 1 <= 2 b = b + a <= 4 b <= 5 ? => true Iter loop: write b <= 4 a = a + 1 <= 3 b = b + a <= 7 b <= 5 ? => false Output: 124
23rd Jun 2019, 1:22 AM
Michail Getmanskiy
Michail Getmanskiy - avatar
+ 7
The loop increases in this sequence 1, 2, 3 adding to the resulted number the final number in the loop is 7 hence the loop stops...so the output will result i 124 there is no where in the loop we can get 125 cause 5 will be no where seen in the set of resulted numbers
23rd Jun 2019, 1:00 PM
John Dhinakar
John Dhinakar - avatar
+ 4
But Diego I don't see any condition in the loop where b==0
23rd Jun 2019, 1:35 AM
eMBee
eMBee - avatar
+ 3
In each loop, "a" increases by 1. After each loop, "b" increases by "a". 1. b == 1. a++ // a == 1 2. b == a+b == 1+1 == 2. a++ // a == 2 3. b == a+b == 2+2 == 4. a++ // a == 3 4. b == a+b == 3+4 == 7 Condition "b <= 5" is False so loop stops. EDIT: Variable "b" equals 1 at the beginning, not 0.
23rd Jun 2019, 1:20 AM
Diego
Diego - avatar
+ 2
Because 2+2==4 and not 5.
24th Jun 2019, 7:41 AM
Sonic
Sonic - avatar