AP® Computer Science Principles · Big Idea 3 · Topic 3.8
REPEAT UNTIL and the Condition Check
A REPEAT UNTIL loop checks its condition before each pass and keeps running while that condition is false, stopping the moment it becomes true.
REPEAT UNTIL tests its stopping condition before every pass through the body, including the very first one. If the condition is already true before the loop ever starts, the body never executes at all. That is the whole point of a pre-check: the loop asks its question first and only acts if the answer tells it to keep going. This also means the number of passes depends entirely on how many times the condition stays false before flipping to true.
Think of the logic in reverse from what the name suggests. REPEAT UNTIL does not mean repeat while something stays true. It means repeat while the condition is false, and stop the instant it becomes true. A loop written as REPEAT UNTIL n > 50 keeps going as long as n > 50 is false, and quits the moment n finally exceeds 50. Mixing this up with a while-true loop is the single most common error, since the two run on opposite logic even though they can be written to produce identical behavior with the condition negated.
REPEAT UNTIL sits next to other iteration tools in the same toolbox: counted loops that repeat a fixed number of times, and conditional loops that check before or after the body. Comparing the pre-check version against a post-check version matters because a post-check guarantees the body runs at least once, while a pre-check can skip the body entirely. Recognizing which check a loop uses is what lets you predict exactly how many times it will run.
Key terms
- REPEAT UNTIL
- A loop that checks its condition before each pass and keeps running as long as that condition is false.
- Pre-condition check
- Testing the stopping condition before the body runs, which can let the body execute zero times.
- Stopping condition
- The expression a loop evaluates to decide whether to stop; REPEAT UNTIL stops once it is true.
- Iteration
- One complete pass through a loop's body.
Watch it explained
- How it worksHow does testing the condition before the body change how many passes the loop makes?
- Worked exampleTrace a REPEAT UNTIL loop doubling n from 3 that stops once n climbs past 50.
- Common mistakeWhy isn't REPEAT UNTIL the same as repeating for as long as a condition stays true?
- Going furtherWhat changes when the stopping condition gets tested after the body rather than before it?
Check yourself
End of topic.