-5

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.

user3646717
  • 1,095
  • 2
  • 12
  • 21

3 Answers3

2

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.

neilvillareal
  • 3,935
  • 1
  • 26
  • 27
1

When i /= 2 becomes 1 then body of the loop will print 1 and increment i by 1. This will never let the value of i /= 2 less than 1 and hence the value of i and the loop will iterate infinitely.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

i keeps getting incremented to 2 and divided by 2 which produces the infinite loop.