Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If i = 9, why does the –i not print a 0 in a C while loop but i– prints a 0 starting from 8?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading