+ 17

Can you explain how this code works?

for(var x=1; x<5; x+=2){ x=x*x;} alert(x) how returns 11?

2nd Sep 2018, 4:45 PM
Mary Aslanyan
Mary Aslanyan - avatar
11 odpowiedzi
+ 17
initializing x to 1 x becomes 1 checking 1<5? true x = x*x x becomes 1*1 ie 1 x +=2 x become 3 checking 3<5? true x = x*x x become 9 x+=2 x become 11 checking 11<5 false exit loop x is 11
2nd Sep 2018, 5:17 PM
code learner
code learner - avatar
+ 11
thank you!
2nd Sep 2018, 6:39 PM
Mary Aslanyan
Mary Aslanyan - avatar
+ 7
First of all x is initialize with value 1. Condition holds true and x = 1*1 = 1. Now x is incremented by 2 i.e x = 3. Condition still holds true and x = 3*3 = 9. Now again x is incremented by 2 i.e x = 11. Now condition => false. Finally it alerts x's value i.e 11. Hope this helps ☺️☺️.
2nd Sep 2018, 5:20 PM
Meet Mehta
Meet Mehta - avatar
+ 4
Base upon the condition of the loop it will multiplied x by x and than it increment x by 2 and check if x is less than 5 , first loops command : multiply x by x x= 1*1=1 loop question: is x less than 5 , answer yes it is ,than increment x by 2 by the way the word increment mean add 2 to the value of x , x=1+2 = 3; loop: command : multiply x by x it self; x= 3*3=9 loop always increment before checking so x+=2 =11; loop question is x lesser than 5 no false ,so break and out put x if asked for now when we request the value of x , x=11; I hope this help you
4th Sep 2018, 4:57 AM
George S Mulbah II
George S Mulbah II - avatar
+ 3
After running loop's code , value is always incremented or decremented and than condition is checked. If condition holds true code is executed else exit the loop.
2nd Sep 2018, 5:30 PM
Meet Mehta
Meet Mehta - avatar
+ 3
First of all x is initialize with value 1. Condition holds true and x = 1*1 = 1. Now x is incremented by 2 i.e x = 3. Condition still holds true and x = 3*3 = 9. Now again x is incremented by 2 i.e x = 11. Now condition => false. Finally it alerts x's value i.e 11.
3rd Sep 2018, 4:23 AM
Ajit Niras
Ajit Niras - avatar
+ 3
for any programming language this will flag error.. Cr: not found x it might be javascript😂😂
3rd Sep 2018, 12:24 PM
Aarav Raj
Aarav Raj - avatar
+ 3
Initialize x to 1 X=x*x return 1 Then x=x+2 so x become 3 And x*x=3*3=9 Then we ajoute 2 to x it become 11 and 11>5 so we exit from the boucle
19th Apr 2019, 11:23 AM
Zakaria Elalaoui
Zakaria Elalaoui - avatar
+ 1
Could you please remove the java tag and put javascript instead? So that people who are looking for java questions won't find your question. Thank you
3rd Sep 2018, 10:24 AM
Daniele Bonomi
Daniele Bonomi - avatar
+ 1
what is the meaning of var.....
3rd Sep 2018, 10:30 AM
Ramalaingam
Ramalaingam - avatar
+ 1
Ramalaingam var is call variable in java script
3rd Sep 2018, 2:36 PM
Dushyant Narula