If x multiplies x in this code, it should result in an even or odd number but here, I don't know why it outputs a prime number | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

If x multiplies x in this code, it should result in an even or odd number but here, I don't know why it outputs a prime number

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

25th Jun 2019, 5:40 AM
eMBee
eMBee - avatar
5 Answers
+ 10
Mofey at the end of the second iteration x has a value of 3*3==9 and just before the third iteration x becomes 9+2==11, so the third iteration never happens because 11<6 is false.
25th Jun 2019, 6:14 AM
Sonic
Sonic - avatar
+ 7
Do you get 11? You are writing x outside and after executing the loop using the final value of x.
25th Jun 2019, 5:56 AM
Sonic
Sonic - avatar
+ 7
Sonic yes I got 11 as the output
25th Jun 2019, 6:01 AM
eMBee
eMBee - avatar
+ 6
Airree why did the iteration of the loop stopped at the second iteration??? Thus, what does the "x<6" contribute to the output of the loop?
25th Jun 2019, 6:04 AM
eMBee
eMBee - avatar
+ 3
Let's run through it. x starts off as 1, then gets squared (still 1), then incremented (3), then squared (9), then incremented again (11) The reason you are confused, that at the end of each iteration, it runs the last part of the for loop even if the condition is false
25th Jun 2019, 5:55 AM
Airree
Airree - avatar