Loops as Controlled Repetition (with Boundaries)
A loop is a structured way to repeat a block of steps while keeping the repetition under control. “Controlled” means two things are always clear: what makes the loop continue and what makes it stop. Good pseudocode loops have visible boundaries: a starting state, a rule for repeating, and a termination condition that will eventually become true.
1) Choosing the Right Loop Type (What Do You Know?)
Use FOR when the count is known
Choose FOR when you know in advance how many times you will repeat, or you can express repetition as a range of indices. This is common for processing every item in a list by position, or repeating exactly N times.
- You know: the number of iterations (or a clear range).
- Typical control: an index variable that moves through a range.
Use WHILE when the condition controls repetition
Choose WHILE when you do not know how many iterations will happen, but you can state a condition that must be true to keep going. The condition is checked before each iteration, so the loop may run zero times.
- You know: a “keep going while …” condition.
- Typical control: a variable that changes each iteration and eventually makes the condition false.
Use REPEAT-UNTIL when it must run at least once
Choose REPEAT-UNTIL when the loop body must execute at least one time (for example, prompting the user for input). The condition is checked after each iteration, and the loop stops when the condition becomes true.
- You know: you must do the steps once, then decide whether to stop.
- Typical control: a validity check performed after reading/processing something.
| Loop type | Best when | Condition checked | Can run zero times? |
|---|---|---|---|
FOR | Iteration count/range is known | Implicit in range | No (if range has values); otherwise effectively zero |
WHILE | Stop depends on a condition | Before each iteration | Yes |
REPEAT-UNTIL | Must execute at least once | After each iteration | No |
2) Writing Loop Headers and Termination Conditions Clearly
Make the loop header answer: “What changes, and when do we stop?”
A reader should be able to point to the loop header and say: “This repeats until X happens.” If the stopping rule is hidden inside the loop body, the loop is harder to verify.
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
FOR: state the range precisely
Use a clear start and end. If the end is inclusive, keep it consistent across your pseudocode. Prefer ranges that match how you describe the data.
FOR i FROM 1 TO n DO ...END FORIf you are iterating through a list, make it obvious whether you are using positions or direct items.
FOR i FROM 1 TO LENGTH(items) DO item ← items[i] ...END FORWHILE: put the continuation condition up front
The WHILE condition should be a simple statement that is true when it is safe and meaningful to run another iteration.
WHILE position ≤ LENGTH(items) AND found = false DO ...END WHILEREPEAT-UNTIL: phrase the stopping condition as a success state
Because REPEAT-UNTIL stops when the condition becomes true, write the condition as something you want to achieve (for example, “input is valid”).
REPEAT ...UNTIL isValid = true3) Loop Invariants in Plain Language (What Stays True Each Iteration)
A loop invariant is a statement that remains true every time the loop reaches the top of an iteration (or, for REPEAT-UNTIL, every time it is about to repeat). Invariants help you reason about correctness: if the invariant is true at the start and remains true after each iteration, then when the loop ends you can trust what the variables mean.
How to write an invariant (beginner-friendly)
- State what the key variables represent so far.
- Connect it to the progress of the loop (index, position, count processed).
- Keep it factual and checkable.
Example invariant phrases:
- “After processing i numbers, sum equals the total of the first i numbers.”
- “All elements before position have been checked and none matched the target.”
- “The last input read is stored in value; isValid correctly reflects whether it meets the rules.”
4) Avoiding Infinite Loops (Update the Control Variables)
An infinite loop happens when the termination condition never becomes true. The most common cause is forgetting to update the variable that the condition depends on (or updating it in the wrong direction).
Checklist to prevent infinite loops
- Identify the control variable(s): which values affect the loop condition?
- Update them every iteration: ensure the update is not skipped.
- Move toward termination: the update must make the stopping condition more likely over time.
- Guard against “stuck” states: if input or data can prevent progress, handle that case explicitly.
Example of a risky WHILE loop (missing update):
position ← 1WHILE position ≤ LENGTH(items) DO IF items[position] = target THEN found ← true END IF // BUG: position never changesEND WHILEFix by updating the control variable:
position ← 1found ← falseWHILE position ≤ LENGTH(items) AND found = false DO IF items[position] = target THEN found ← true ELSE position ← position + 1 END IFEND WHILENote: the update can be placed outside the IF if you want it to happen regardless; choose the structure that makes the logic easiest to verify.
5) Using BREAK/CONTINUE Sparingly (with Explicit Justification)
BREAK exits a loop immediately; CONTINUE skips to the next iteration. They can make code shorter, but they can also hide the loop’s boundaries by adding extra exit/skip paths. Use them only when they make the intent clearer than rewriting the loop condition.
When BREAK is justified
- You are searching for a match and want to stop as soon as it is found.
- Continuing would be wasted work and the early exit is the main point.
When CONTINUE is justified
- You are filtering items and want to skip invalid/unwanted cases early.
- It reduces nesting and keeps the “main path” readable.
Even when using BREAK/CONTINUE, keep the termination story obvious: a reader should still be able to explain why the loop ends.
Step-by-Step Examples
Example A: Summing Numbers (Known Count → FOR)
Goal: compute the sum of the first n numbers (1 through n).
Why FOR: the number of iterations is known (exactly n).
Invariant (plain language): at the start of each iteration with index i, sum equals the total of numbers 1 through i-1.
INPUT nsum ← 0FOR i FROM 1 TO n DO sum ← sum + iEND FOROUTPUT sumStep-by-step for n = 4:
| i | sum before | operation | sum after |
|---|---|---|---|
| 1 | 0 | sum ← 0 + 1 | 1 |
| 2 | 1 | sum ← 1 + 2 | 3 |
| 3 | 3 | sum ← 3 + 3 | 6 |
| 4 | 6 | sum ← 6 + 4 | 10 |
Example B: Scanning a List for a Match (Unknown Position → WHILE or FOR)
Goal: determine whether target appears in items.
Choosing the loop:
- If you want to express “keep checking until found or out of items,”
WHILEmakes the stopping rule explicit. - If you prefer a fixed pass through indices,
FORworks, often withBREAKfor early exit.
Option 1: WHILE with clear termination condition
Invariant: all positions before position have been checked and none matched target; found is true only if a match has been seen.
INPUT itemsINPUT targetposition ← 1found ← falseWHILE position ≤ LENGTH(items) AND found = false DO IF items[position] = target THEN found ← true ELSE position ← position + 1 END IFEND WHILEOUTPUT foundStep-by-step idea: each iteration either finds the target (sets found to true, which stops the loop) or advances position by 1 (which moves toward the end and guarantees progress).
Option 2: FOR with BREAK (explicit justification: stop immediately when found)
INPUT itemsINPUT targetfound ← falseFOR i FROM 1 TO LENGTH(items) DO IF items[i] = target THEN found ← true BREAK // justified: no need to scan remaining items once found END IFEND FOROUTPUT foundExample C: Repeating Input Prompts Until Valid (At Least Once → REPEAT-UNTIL)
Goal: keep asking for an integer in a valid range (for example, 1 to 10) until the user provides one.
Why REPEAT-UNTIL: you must prompt at least once before you can test validity.
Invariant: after each prompt, value stores the most recent input and isValid correctly reflects whether it meets the rules.
isValid ← falseREPEAT OUTPUT "Enter a number from 1 to 10:" INPUT value IF value ≥ 1 AND value ≤ 10 THEN isValid ← true ELSE OUTPUT "Invalid. Try again." isValid ← false END IFUNTIL isValid = trueOUTPUT "Accepted:"OUTPUT valueStep-by-step behavior:
- First iteration always happens: prompt → read → validate.
- If invalid, the loop repeats because
isValidis false. - When valid,
isValidbecomes true and the loop stops immediately after that iteration.