+ 1
Lets go through both loops: First Loop: You initialize i with 7 -> i+2 = 9 -> i is printed(9) -> i is incremented, which means i is now 10 -> condition is valid, loop goes on -> i+2 = 12 -> i is printed(12) -> i is incremented again, now it is 13 -> condition is false, loop in terminated. Notice here that i is 13, as it is in second loop! You just dont see it anymore because the print-statement usually happens after the incrementation! You can see this by yourself by adding a last print-statement after the loop like in example two. Okay, now for the second loop: You initialize i with 1 again -> i+2 = 3 -> increment, i = 4 -> i+2 = 6 -> increment, i = 7 -> i+2 = 9 -> increment, i = 10 -> condition is still valid since i == 10, so loop goes on -> i+2 = 12 -> increment, i = 13 -> condition is checked, now it is false -> loop is terminated. And now you print i, which is obviously 13 now. To summarize: Both i's were equal to 13 in the end, the different output is simply caused by when you print the i.
2nd Nov 2017, 4:46 PM
Shadow
Shadow - avatar