#include<stdio.h> 
int main()
{
int x=5;
int y=50;

do{
x = x + 10; 
}while (x <y);
printf("%d\t%d", x,y);
}

I wonder why i compile is 55 50
why not 15 50???

Dani AI

Generated

As 's example shows, a post-test loop (do/while) runs the loop body first and then evaluates the condition. 's reply points in the right direction: x is increased by 10 repeatedly, and the condition is checked after each increment. That sequence makes x reach 55 before the loop stops, so the final print shows 55 and 50.

Step-by-step (starting x = 5):

  • after 1st iteration: x = 15 (15 < 50 → continue)
  • after 2nd iteration: x = 25 (25 < 50 → continue)
  • after 3rd iteration: x = 35 (35 < 50 → continue)
  • after 4th iteration: x = 45 (45 < 50 → continue)
  • after 5th iteration: x = 55 (55 < 50 is false → exit)

To get different behavior, use a pre-test loop or a single conditional. Examples:

/* print each step until x >= y */
int x = 5, y = 50;
while (x < y) {
    x += 10;
    printf("%d\t%d\n", x, y);
}
/* do exactly one increment when x < y */
int x = 5, y = 50;
if (x < y) x += 10;
printf("%d\t%d\n", x, y);  /* prints 15 50 */

Troubleshooting tips: put a printf inside the loop to watch x change, or step through with a debugger (gdb/IDE). Also add a newline in printf for readable output.

The loop continues as long as x is less than y. It isn't until x = 55 that the test fails.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.