int i;
i = 9;
while (--i)
{
printf("%d", i);
}
The above piece of code prints 87654321. (This means the decrement happens first before printing as we have the pre-decrement sign before the i and we do not print the 0 because the while loop evaluates the 0 as false.)
Now, how come in this next piece of code, the output starts from 8 and ends at 0? (876543210)
int i;
i = 9;
while (i--)
{
printf("%d", i);
}
Since the second code has a post decrement, I was expecting it to start printing from 9 without the 0 at the end since the while loop in the first example evaluated 0 as false. Following the pre-decrement and post decrement rule, why is the second code giving such an output?
>Solution :
i = 1;
while (--i) // evaluates to while (0)
// condition is false so the while loop stops
i = 1;
while (i--) // evaluates to while (1), afterwards i gets decremented to 0
// condition is true so we enter the loop body