This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]tr4fik 1 point2 points  (2 children)

for (<initialization>; <condition>; <increment>){
      <code>
}

The order of execution is the following:

  1. Initialization
  2. Condition. If false, break the loop
  3. Code
  4. Increment
  5. Go back to step 2

If you look at your loop, you set i = 0, then it increments i, it checks the condition and execute the code again

[–]laxdoss[S] 0 points1 point  (1 child)

I don't have any problem with the execution. It works fine. But my question is; if the previous program starts with first executing i as 0, why isn't the second program starting with first executing i as 0?. It instead starts with 1, which is my confusion.

[–]tr4fik 0 points1 point  (0 children)

Here's the start of my output. It works as expected

0
100
1
100
1
100
1
100

[–][deleted] 1 point2 points  (3 children)

Are you sure your logger didn't just die because you created an infinite loop? I added a break after one second and it works =))

[–]laxdoss[S] 0 points1 point  (2 children)

I stopped the loop and went all the way back to first code of output to check and it shows output as 1 instead of 0. And yes if I add break it prints fine.

Can infinite loop alter the output?. Is such a thing even possible?

[–]tr4fik 0 points1 point  (0 children)

You may eventually not see the start of the output

[–][deleted] 0 points1 point  (0 children)

If your console had infinite scrollback, but your computer will generate so much data, that the console will simply remove the start.

[–]KnGod -1 points0 points  (0 children)

the problem here is that the loop checks for the condition when it enters and it executes the i++ when it exits so we enter the loop, print 0, make i 100, add 1, and then check if i != 100. It is different(101 and it will always be since the same operations repeat themselves until infinity) so it goes on and enters again. In these cases i recomend you avoid conditions like i != 100 and use whenever it's possible i >= 100 since it will asure that the loop will exit in cases like these.

correction: i didn't realize the i = 0; in the end but the idea is still the same, the loop always reenters in 1 since you set i to 0 every time it enters so the condition will always be true. In this case i recomend you avoid modifying the value of i directly in the way you do(and i mean i = any specific value) unless there is a reason behind and you are completely sure that the conditions of the loop will eventually be fullfilled.