Why is the value of "i" in my code 5 after setting its value to be less than 5 in the loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Why is the value of "i" in my code 5 after setting its value to be less than 5 in the loop?

for(i=0; i<5; i++); {} document.write(i);

27th Jun 2019, 2:17 PM
eMBee
eMBee - avatar
9 Answers
+ 9
Mofey Consider the steps of the for loop... 1. Check if the break condition is true. 2. Execute the block or exit the loop. 3. Iterate the value of `i`. In this loop, the break condition is true while i < 5. This means that the block of code in the loop will run when i is 0, 1, 2, 3, and 4. Now... you are probably thinking that `i` should be 4, not 5. But, remember, `i` needs to be incremented to 5 for the break condition to occur. This last increment happens in step #3 with i++, after step #2 executes the block for the last time, when `i` was 4. Therefore, `i` reflects the value at the time of the break condition, which is 5.
27th Jun 2019, 2:57 PM
David Carroll
David Carroll - avatar
+ 12
The condition in the for loop is that the code will execute if and only if value of i is less than 5... Until this condition is true (i is less than 5 in the first 5 steps) the code will execute... When i reaches 5, i is no longer smaller than 5... So the statement that i<5 becomes false... And then when the condition is checked, there are no true conditions... I think Qasem meant to say that...🙂
28th Jun 2019, 5:19 PM
Humayra🇧🇩
Humayra🇧🇩 - avatar
+ 9
Suppose that i is 4. Then i++ increments it by one and when condition is checked there is no true condition and loop won't be executed. But i is 5 now
27th Jun 2019, 2:32 PM
Qasem
+ 8
Wow David Carroll, once again, Woaw, thank you very much for that explanation because I was actually thinking that the loop is meant to stop at 4 since `i` was set to be less than 5
27th Jun 2019, 3:03 PM
eMBee
eMBee - avatar
+ 7
The loop runs as long as `i` is smaller than 5. It stops when `i` hits 5. So, for the loop to stop, `i` has to become 5 - otherwise `i` would be smaller than 5 and the loop continues.
27th Jun 2019, 2:46 PM
Schindlabua
Schindlabua - avatar
+ 7
Condition is : i<5. When i==5, this condition is false.
29th Jun 2019, 6:05 AM
Sonic
Sonic - avatar
+ 5
Qasem, what do you mean by "when condition is checked, there is no true condition" ??
27th Jun 2019, 2:39 PM
eMBee
eMBee - avatar
+ 5
For loop has three parts. Initial value, counting, and condition check. Those are executed in order which I wrote. For (initial value; condition check to run loop; counter)
27th Jun 2019, 2:42 PM
Qasem
+ 4
I is OUTSIDE THE LOOP (4 ++ = 5) 🤗🤗
29th Jun 2019, 6:26 AM
Sanjay Kamath
Sanjay Kamath - avatar