confused i loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
13th Sep 2019, 11:33 AM
Ahmad Ali
Ahmad Ali - avatar
1 Answer
+ 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.
13th Sep 2019, 12:41 PM
Shane Overby
Shane Overby - avatar