How to increment a counter for a while loop within the loop?

King Sutter picture King Sutter · Feb 2, 2017 · Viewed 13.5k times · Source

I have a feeling I'm gonna feel really stupid here, but I'm just learning about using ++ and -- to increment and decrements variables for while loops, and was wondering why this piece of code works and why this doesn't?

Bad code:

int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

The bad code outputs zeros indefinitely.

Working code:

int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

The idea is for the output to be 012345678910 but even in the working code, it starts at 1 and goes to 10, instead of starting at 0. Even though the initial value of ctr is 0.

Answer

Sourav Ghosh picture Sourav Ghosh · Feb 2, 2017

In the first case

while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

the while loop body is considered only the printf() statement. ctr=ctr+1; is not part of the loop body. So you have an unchanged variable in loop condition check, which makes it infinite loop.

You need to enclose both the statements in a block scope, using {} so that both the statements become part of the loop body. Something like

while (ctr < 10) {
  printf("%d",ctr);
  ctr=ctr+1;
}

will do.


In the second case

int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

ctr is already incremented as the side effect of the postfix increment operator, in the while condition checking expression. Thus, while printing the value, the already incremented value is being printed.