+ 3
confused i loop
why we got 5 in this code? https://code.sololearn.com/W5ZxCLX0K7Mi/?ref=app
1 Resposta
+ 6
In your 'for' loop you're implicitly declaring the 'i' variable, which makes it a global variable, which you must be aware of since you're using the 'i' variable after the 'for' loop.
Here's a breakdown of the execution workflow for your code:
The first iteration of the 'for' loop starts with 'i' having a value of 0.
'i' is then incremented in the loop's body (i = i + 1), making it's value 1.
Once execution of the loop's body is complete 'i' is incremented again (i++), making it's value 2.
2 is less than 3, so the loop's body is executed again.
Again 'i' is incremented in the loop's body (i = i + 1), bringing it's value to 3.
And again 'i' is incremented once execution of the loop's body is complete (i++), bring it's value to 4.
4 is greater than 3, so the loop is exited.
The following 'if' statement evaluates to true, since 4 % 2 equals 0, and then 'i' is incremented once more, bringing it's value to 5.