A while loop checks its condition before the first pass, so its body might never run. Sometimes you want the opposite: run the body once, then decide whether to repeat. That is what a do-while loop is for.
A do-while loop puts the body first and the condition at the end:
Integer count = 1;
do {
System.debug('Count is ' + count);
count++;
} while (count <= 3);
The body always runs at least once because the condition is not checked until the end of the first pass.
Compare the two loop types when the condition starts out false:
Integer count = 5;
// This body never runs
while (count <= 3) {
System.debug('while ran');
}
// This body runs one time
do {
System.debug('do-while ran');
} while (count <= 3);
The while loop skips its body entirely. The do-while loop runs its body one time before the condition stops it.
A do-while loop ends with a semicolon after the while condition. Forgetting it is a common beginner mistake that leads to a compile error.
Use a do-while loop when the work must happen at least once, such as showing a menu before asking whether to show it again, or processing a value before checking whether more remain.