# Infinite 'for' loop

This is a discussion on Infinite 'for' loop within the C Programming forums, part of the General Programming Boards category; Code: int i = 1; for ( ; ; ) if (i >= 10) break; else if (i % 2) ...

1. ## Infinite 'for' loop

Code:
```int i = 1;
for ( ; ; )
if (i >= 10)
break;
else
if (i % 2)
i += 2;
else
i -= 2;
printf("%d", i);```
I don't know how this code works, but the output is 11 so I guess the condition (i%2) is true so i is incremented by 2 until it's 11, which is >=10 and then the loop exits with the break statement.
Can anyone give me some details about how this code is executed please?

2. You seem to have the basic idea right though. What exactly are you having problems with?

3. Originally Posted by laserlight
You seem to have the basic idea right though. What exactly are you having problems with?
Thanks for clarifying my guess. I just don't know what (i%2) means, and why it's true in this case.

4. i%2 is the remainder on dividing the integer i by 2. If i is a multiple of 2, i%2 is zero. Otherwise it is 1.

Depending on age of your compiler, there are some caveats if i is negative (since some aspects of integer division involving negative values were implementation-defined in the 1989 C standard and earlier, although this was changed in the 1999 C standard).

5. Originally Posted by grumpy
i%2 is the remainder on dividing the integer i by 2. If i is a multiple of 2, i%2 is zero. Otherwise it is 1.

Depending on age of your compiler, there are some caveats if i is negative (since some aspects of integer division involving negative values were implementation-defined in the 1989 C standard and earlier, although this was changed in the 1999 C standard).
Yes, but I still don't understand the if statement, I've seen if (i%2 == 0) .... but not if(i%2)

6. When doing any logical test, a zero value is false, and a non-zero value is true.

So "if (i%2)" is shorthand for "if (i%2 != 0)". This is true in all conditionals (loop conditions, ternary ?:, etc).

7. Originally Posted by grumpy
When doing any logical test, a zero value is false, and a non-zero value is true.

So "if (i%2)" is shorthand for "if (i%2 != 0)". This is true in all conditionals (loop conditions, ternary ?:, etc).
Great explanation, thank you!

Simply put in diagnostic printfs(). For each pass through the loop, print out i. You can also put in "Here"s to indicate which branch of the if is being taken.