doWhile
Syntax
do{
statements
}
while (conditions);
Details
The do-while loop first executes the do statement, then checks the condition at the bottom of the loop. This guarantees the loop is executed at least once. Both parentheses () after while and braces { } after do are mandatory for do-while statements.
Note that if conditions is NULL or !NULL, it is treated as false.
Difference from the while loop: while evaluates the condition before executing the loop body, so the loop body may not be executed at all. By contrast, do-while executes the loop body before evaluating the condition, ensuring that the loop body is executed at least once. For details, see while.
Examples
x=1
do {x+=2} while(x<100)
x;
// output: 101
x=1
y=0
do {x+=y; y+=1} while(x<100 and y<10);
x;
// output: 46
y;
// output: 10
// while: when the condition is not met, the loop body is not executed at all
x = 100
while (x < 10) {
print x
x += 1
}
// No output, because the initial condition x < 10 is false
// do-while: even if the condition is not met, the loop body is executed once
x = 100
do {
print x
x += 1
} while (x < 10)
// output: 100
// The condition is checked only after the loop body is executed once
