+ 1

Why is the output 11 & not 9?

var x = 1; for(; x < 6; x += 2) { x = x * x; } alert (x);

19th Feb 2018, 7:01 PM
Briaה‎
4 odpowiedzi
+ 2
Dont forget that x+=2 will run at end of every iteration start with x=1 1) x*x=1 x+2= 3 (3<6 continue) 2) x*x=9 x+2=11 (11 > 6 stop here) stop
19th Feb 2018, 7:13 PM
KrOW
KrOW - avatar
+ 2
First round: 1 * 1 = 1 2nd Round: 3*3 = 9 Then x is incremented by 2 and the condition is checked: x < 6 ? --> False, x is 11 now.
19th Feb 2018, 7:12 PM
Jonas Schröter
Jonas Schröter - avatar
+ 2
I am use this form for debug my codes ,inclusive used gives last answer. var x = 1; for (var limit = 6; x < limit; x += 2) { alert("Before mult: " + x); x = x * x; alert("after mult: " + x); } alert(x);
19th Feb 2018, 8:20 PM
J G
J G - avatar
0
@(G J) last output will be 11 as excepted.... what you get??
19th Feb 2018, 8:30 PM
KrOW
KrOW - avatar