+ 4

Could someone please explain me this code? This is javascript

var x =1 for (; x<6; x+=2) { x=x*x; } document.write(x);

7th Nov 2016, 7:09 PM
Andrés Amaya
Andrés Amaya - avatar
5 odpowiedzi
+ 15
Step by step: x is initialized at 1. x is lower than 6, so we enter the loop. x is set to 1*1 = 1. x is incremented by 2 (x is now 3). x is still under 6, so we loop again. x is set to 3*3 = 9. x is incremented by 2 (x is now 11). x is not lower than 6, so we exit the loop. x is printed (value: 11). If you didn't get it right, it's probably because you forgot that the increment was done at the end of the loop before checking the condition. In real life, if you change the value of the loop variable inside the loop (besides the increment or decrement), I recommend to use a while loop, it is less confusing that way.
7th Nov 2016, 7:37 PM
Zen
Zen - avatar
+ 6
thank you great answers!
12th Nov 2016, 11:53 AM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 5
first iteration x = 1 x=1*1=1 second iteration x=1+2=3 (the x+=2 statement) x=3*3=9 x is no longer smaller than 6 therefor the loop is done but an increment of +2 will happen once more so the end value of x should be 11
7th Nov 2016, 7:31 PM
Burey
Burey - avatar
+ 4
Ahhh for loops, I had so much trouble understanding them at first. var x=1 This sets x equal to 1 for (; x<6; x+=2) { I will split the "for" line up into 3 parts ; The empty ; at the beginning is where you can declare a variable to be used in the loop. Since x is already defined, this is blank. x<6; The for loop will continue looping as long as x is less than 6. x+=2) { Increment x by two whenever the loop has completed once. I like to look at loops as being structured like this: for (DECLARE;CONDITION;INCREMENT) { //Your loop here } ANYWAYS, inside the for loop: x=x*x; This multiplies x to itself, effectively squaring it. document.write(x); Writes the value of x to the document. If you think I made a mistake or if there is something you don't quite understand, please let me know.
7th Nov 2016, 7:32 PM
Lux
Lux - avatar
+ 3
thank you very much guys
7th Nov 2016, 10:02 PM
Andrés Amaya
Andrés Amaya - avatar