Pre-Test Loop
Image: Taylor, CC BY-SA 4.0, Wikimedia Commons
In short: A loop where the exit condition is checked BEFORE every iteration — if it’s already false on the first check, the loop body isn’t executed at all.
In more detail: While loops and for loops are typically pre-test. The opposite is the post-test loop (do...while), which always executes the code block at least once, because the condition is only checked at the end. The choice between the two depends on whether “at least one iteration” needs to be guaranteed.
In Depth
while (condition) { // check BEFORE the first iteration
// code block
}If the condition is already false at the very first check, the code block runs NOT ONCE at all — this fundamentally distinguishes the pre-test loop from the post-test variant. A typical example where this matters:
list = [] // empty list
for element in list:
process(element) // never called, list is emptyFor an empty data structure, exactly this behaviour (doing nothing) is usually what’s desired — if a post-test loop were used instead, you’d have to manually check beforehand every time whether elements even exist, to prevent a faulty first iteration on empty data.
Most loop types used in everyday work (while, for, for-each over a collection via Iterator) are pre-test — the post-test do...while loop is the clear exception and is correspondingly needed less often, usually only where “execute at least once” is explicitly desired (e.g. a user input you want to ask for at least once, before you can check it for the first time).
Cross-language implementation
Practically every widespread programming language implements pre-test loops following the same basic pattern, just with slightly different syntax: while (condition) { ... } in Java/JavaScript/C, while condition: in Python (no parentheses, indentation instead of curly braces). The underlying concept — check condition, then possibly execute, repeat — stays identical across all languages, only the specific notation differs.
Pre-test for for-each loops
A for-each loop over a collection or an array is also fundamentally pre-test at its core, even though this is less obvious at first glance than for a classic while loop: internally, an iterator checks before every iteration whether another element exists (hasNext()), before it even returns it — for an empty collection, this check immediately returns “no”, and the loop body accordingly doesn’t run at all.
See also: Loops, Post-Test Loop, While Loop, Iterator