#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???
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):
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.