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++; }
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
+ 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
+ 4
But Diego I don't see any condition in the loop where b==0
+ 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.
+ 2
Because 2+2==4 and not 5.