+ 1

Quick question from challenge

I was ‘challenged’ by Sololearn and this was one of the questions. Var x = 1 For (; x < 6; x+=2) { x=x*x } Apparently the answer is 11, but I have no idea how. Can anyone explain?

11th Feb 2022, 6:51 AM
mark leager
2 Antworten
+ 5
Simple. Let's see the control flow of this snippet of code: Iteration 1: x=1, condition passes and enters the loop x=x*x=1*1=1 x+=2 increments x by 2 and now x is 3(1+2) Iteration 2: x=3, condition passes and enters the loop again x=x*x=3*3=9 x+=2 ie. x=x+2=9+2=11 Iteration 3: x=11, condition fails and exits the loop with x holding the value 11. I hope you got it. Feel free to ask if you get any doubts in this explanation
11th Feb 2022, 6:59 AM
Rishi
Rishi - avatar
+ 3
Nvm i figured it out. The order is: -original variable x is set (1) -x is checked against x<6 (true) -THEN code block is run (x=x*x or x=1x1) -NOW is add x=x+2 Edit: Thanks Rishi! You posted at the perfect time lol I really appreciate your thorough breakdown!
11th Feb 2022, 6:59 AM
mark leager