0
I am having trouble understanding this code. I get 10 as the answer, not 7. Can someone please explain?
var x = 1; for(;x<5;x++) {x+=x } alert (x);
3 Answers
+ 3
x=1.
for x<5 true
x=x+x=1+1=2
x++ =>x=x+1=3
3<5 true
x=x+x=3+3=6
x++ =>x=7
7<5 false.
Alerts 7
So 7 only not 10...
You may missing something in code if you got as 10..
+ 1
format of if statement is:
if (
<statement_to_be_ran_once_at_sart :: initialization (usually init of counter variable)>;
<condition_evaluated_at_end_of_each_iteration :: if false quit the loop>;
<statement_to_be_executed_at_end_of_each_iteration :: usually counter incrementation>
) {
<code_executed_at_each_iteration>
}
Anyway, it's totally valid to have one to all of this fourth part empty... for dumb example this work, even if infinite loop doing absolutly nothing:
for (;;);
(curly braces can be avoided if only one statement inside it -- could be many expressions comma "," separated -- but all semi-colons ";" are mandatory)
0
My mistake was that I was incrementing before I executed the code in the curly brackets.