Search code examples
cloopsfor-loopindefinite

What output does the following for statement produce in C?


I anticipated it would produce:

10 5 3 2 1

but instead it prints

10 5 3 2 1 1 1 1 1 1 1 1 1...

Why?

#include <stdio.h>

int main(void)
{
    int i;

    for(i = 10; i >= 1; i /= 2)
        printf("%d ", i++);

    return 0;
}

2 is printed, then one is added making it 3, divided by 2 is 1. As 1 is equal to 1, 1 is printed and then one is added making it 2, divided by 2 is 0. As 0 is less than 1, the loop should end.


Solution

  • When i is 1, you print it with the printf statement. Then i gets incremented (via the ++ operator in your printf statement). Then i /= 2 is performed, which results to i = 2 / 2 which results to 1. This satisfies your condition i >= 1, making it an infinite loop.