do-while Loop
Image: Taylor, CC BY-SA 4.0, Wikimedia Commons
In short: The classic syntax form of the post-test loop — executes the code block and only afterwards checks whether it should run again.
In more detail: The structure do { ... } while (condition); reverses the principle of the while loop: instead of “check, then execute”, it’s “execute, then check”. This means the block always runs at least once — practical for input validation, where the user first has to enter something before it can be checked whether the input was valid.
In Depth
do {
input = ask_user("Number between 1 and 10: ")
} while (input < 1 OR input > 10)This example shows the classic use case: you CAN only check the condition (is the input valid?) AFTER some input even exists — with a normal while loop, you’d therefore have to artificially duplicate the input “before” the loop, so a value already exists at the first condition check:
// Equivalent with while, but with duplicated input logic:
input = ask_user(...)
while (input < 1 OR input > 10):
input = ask_user(...)The do-while variant avoids this code duplication, because the guarantee “runs at least once” is already built into the structure itself. That’s exactly the one, but decisive, difference from a normal while loop: with while, the code block can run ZERO times (if the condition is already false from the start), with do-while it’s guaranteed to run at least ONCE, no matter what the condition looks like at the start — because it’s only checked at the end.
Not every language offers do-while as its own language construct (Python, for example, doesn’t) — there, the behaviour is usually emulated with an infinite loop plus an explicit break at the end:
while True:
input_value = ask_user(...)
if 1 <= input_value <= 10:
breakIn practice, do-while is encountered less often than while or for, because the use case (“the block has to run at least once before the condition can even be checked”) is more specific — still, it’s worth knowing the pattern, because in exactly this case it enables more readable code with no duplication.
See also: Post-Test Loop, While Loop, Loops