# Infinite 'for' loop

• 02-24-2013
drawar
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?
• 02-24-2013
laserlight
You seem to have the basic idea right though. What exactly are you having problems with?
• 02-24-2013
drawar
Quote:

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.
• 02-24-2013
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).
• 02-24-2013
drawar
Quote:

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)
• 02-24-2013
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).
• 02-24-2013
drawar
Quote:

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! :)
• 02-24-2013
Malcolm McLean