Chapter 6 Key Takeaways
The Three Loop Constructs
-
REPEAT..UNTILis a post-test loop. The body executes at least once. The loop stops when the condition becomesTrue. Nobegin..endneeded —repeatanduntilare the delimiters. -
WHILE..DOis a pre-test loop. The body may execute zero times. The loop continues while the condition isTrue. Requiresbegin..endfor multiple statements. -
FOR..TO/FOR..DOWNTOis a counted loop. The number of iterations is determined before the loop starts. The loop variable is managed automatically. Do not modify it inside the body. Its value is undefined after the loop.
Choosing the Right Loop
- Know the count? Use
FOR. - Must run at least once? Use
REPEAT..UNTIL. - Might run zero times? Use
WHILE..DO.
Condition Logic Trap
UNTILmeans stop when true (loop while false).WHILEmeans continue when true (loop while true).
These are logical inverses. Mixing them up is a common source of bugs.
Essential Patterns
| Pattern | Purpose | Typical Loop |
|---|---|---|
| Counter | Count items meeting a condition | FOR |
| Accumulator | Running total or product | FOR or WHILE |
| Sentinel | Process input until special value | WHILE (with priming read) |
| Search | Find a specific item | WHILE (with flag or Break) |
| Menu | Repeated user interaction | REPEAT..UNTIL |
| Input validation | Ensure correct input | REPEAT..UNTIL |
The begin..end Trap
WHILE..DO and FOR control only a single statement. If you have multiple statements in the loop body, you must wrap them in begin..end. Forgetting this is the number-one beginner mistake with loops and the most common cause of accidental infinite loops.
Debugging Essentials
- Infinite loop? Check: Is the loop variable being updated? In the right direction? Can the condition ever become true/false as needed?
- Off-by-one? Check: Is the boundary
<or<=? Is the range inclusive or exclusive? Does the loop start and end at the right values? - Trace with WriteLn: Insert
WriteLnstatements to display loop variables at each iteration. Remove them after debugging. - Desk-check first: Trace through the loop by hand with small input before running the program.
Nested Loops
The inner loop completes all its iterations for each iteration of the outer loop. Total iterations = outer count multiplied by inner count. Use different variable names for each loop level.
Break and Continue
Available in Free Pascal but not standard Pascal. Break exits the innermost loop. Continue skips to the next iteration. Use both sparingly — clear loop conditions are usually preferable.
Key Rules for FOR Loops
- Loop variable must be an ordinal type (not
Real). - Do not assign to the loop variable inside the body.
- The loop variable is undefined after the loop exits.
- Start and end values are evaluated once, before the first iteration.
- If start > end (for
TO) or start < end (forDOWNTO), the body never executes.