+ 2

The loop ans is 12. Need explanation please

k=6 for (var i=0 ; i < k ; i++) { k+=0.5; } alert(i);

6th Oct 2021, 11:38 AM
ShadowCipher
ShadowCipher - avatar
10 Answers
6th Oct 2021, 11:58 AM
ShadowCipher
ShadowCipher - avatar
+ 2
6th Oct 2021, 11:54 AM
ShadowCipher
ShadowCipher - avatar
+ 2
Kapama, Joshua, No problem 👍 And happy learning!
6th Oct 2021, 12:07 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 2
David Stevens, please post your question in a new thread.
7th Oct 2021, 2:29 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
The answer is 12 instead of 9, because every time you add 0.5 to the k, your loop condition is altered, because k changes, so it takes twice as long to go through the loop. That's why the answer is 12...
6th Oct 2021, 11:48 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
So sorry Aleksei Radchenkov , if the value of k changes everytime you add up 0.5. Wasn't it suppose to be infinite loop then?? How does the loop get stop
6th Oct 2021, 11:51 AM
ShadowCipher
ShadowCipher - avatar
+ 1
Kapama, Joshua, Nope.. 'i' variable gets increased by 1 each iteration, while k gets increased by 0.5. So it will just take twice as long, but it won't be infinite...
6th Oct 2021, 11:54 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
David Stevens You're question is popular just search it in Q&A. Its good to post in a new thread to get answers quickly, it is not adviced to post question in another thread like this.
7th Oct 2021, 3:19 AM
ShadowCipher
ShadowCipher - avatar
- 1
Help how does variables wrk
7th Oct 2021, 12:11 AM
David Stevens
- 1
Im trying to learn coding from complete scratch
7th Oct 2021, 12:13 AM
David Stevens