Part I — Foundations · Chapter 3 · Lesson 4 of 5 · 8 min read
Lesson 4: break, continue, Nesting, and Defensive Termination
Lesson level: Foundation
Purpose: Control loop execution precisely without hiding progress, corrupting results, or creating unbounded behavior.
Learning objectives
By the end of this lesson, you should be able to:
- use break to leave the nearest loop;
- use continue to skip the remainder of the current iteration;
- predict control transfer in nested loops;
- preserve updates and invariants when iterations are skipped;
- design bounded searches and retries;
- distinguish normal completion, early success, and exhaustion;
- limit nested-loop work defensively; and
- debug premature exits and stalled loops systematically.
4.1 Why explicit loop control exists
Most loops should finish through their ordinary condition or iterable exhaustion. Sometimes the body discovers that no more work is needed or that the current element should not receive the remaining processing. PeaLang provides break and continue for these cases.
Use them deliberately. A control-transfer statement should make the algorithm easier to understand, not compensate for unclear conditions or missing progress logic.
4.2 break
break exits the nearest enclosing loop immediately. Statements later in that body and all future iterations of that loop are skipped.
let found = null
for value in [4, 7, 9, 12] {
if value >= 9 {
found = value
break
}
}
print "Found: {found}"
The loop visits 4, 7, and 9. When 9 satisfies the condition, found is assigned before break transfers control to the statement after the loop. The value 12 is never visited.
4.3 Record the result before breaking
An early exit should leave enough state to explain why the loop stopped. Assign the match, status, reason code, or completion flag before executing break.
After the loop, distinguish “found” from “not found” by inspecting that state rather than assuming break occurred.
4.4 continue
continue skips the remaining statements in the current iteration and proceeds to the next iteration of the nearest loop.
let total = 0
for value in [3, -1, 5, -2] {
if value < 0 {
continue
}
total += value
}
print "Total: {total}"
Negative values skip the accumulation statement. The final total is 8.
4.5 continue in a while loop
Continue is more dangerous in a while loop because it can skip the update that guarantees progress.
let value = 0
while value < 5 {
value += 1
if value == 3 {
continue
}
print value
}
The progress update occurs before the possible continue, so every iteration advances. The loop prints 1, 2, 4, and 5.
If value += 1 appeared after the continue, value would remain 3 forever. Place essential progress updates before any path that can skip the rest of the body.
4.6 Invariants with continue
A continue path must preserve the same loop invariant as an ordinary path. Before continuing, complete any required bookkeeping, counters, or resource accounting that the invariant assumes.
For example, if an invariant states that processed equals the number of inspected records, increment processed before a continue that rejects the current record.
4.7 break and post-loop state
Break ends the loop without proving that the ordinary condition became false or that the iterable was exhausted. The state after the loop must therefore encode the exit reason.
| Exit mode | Evidence |
|---|---|
| Normal exhaustion | No match or stop flag was recorded |
| Early success | Found value or success flag is present |
| Defensive limit | Attempt counter reached its maximum |
| Invalid state | Error status or reason code was recorded |
4.8 Nested loops
A loop may contain another loop. The outer loop selects one outer value; the inner loop then runs through its values for that outer context.
for row in range(1, 3) {
for column in range(1, 4) {
print "({row}, {column})"
}
}
The outer loop produces rows 1 and 2. For each row, the inner loop produces columns 1, 2, and 3, resulting in six coordinate pairs.
4.9 break targets the nearest loop
Inside nested loops, break exits only the innermost active loop.
for row in range(1, 4) {
for column in range(1, 4) {
if column == 2 {
break
}
print "({row}, {column})"
}
}
For every row, the inner loop prints column 1 and breaks when column becomes 2. The outer loop continues with the next row.
4.10 continue targets the nearest loop
Inside nested loops, continue skips the remainder of the current iteration of the innermost active loop.
for row in range(1, 3) {
for column in range(1, 4) {
if column == 2 {
continue
}
print "({row}, {column})"
}
}
Columns 1 and 3 are printed for each row. The outer iteration is unaffected.
4.11 Leaving multiple loop levels
Because break affects only the nearest loop, use explicit state when an inner match must stop outer processing.
let found = false
for row in range(1, 4) {
for column in range(1, 4) {
if row == 2 and column == 3 {
found = true
break
}
}
if found {
break
}
}
The inner break exits the column loop. The outer condition then checks found and breaks the row loop. The flag records why both loops stopped.
4.12 Nested-loop cost
If an outer loop runs m times and the inner loop runs n times for every outer value, the body can execute up to m * n times. Add further nested levels carefully because work multiplies.
Bound each dimension, reject oversized inputs at the host boundary, and avoid printing or allocating unbounded results inside nested loops.
4.13 Bounded search pattern
A bounded search examines candidates until it finds a match or exhausts the candidate set.
let target = 14
let found = null
for value in [5, 9, 14, 20] {
if value == target {
found = value
break
}
}
if found != null {
print "FOUND: {found}"
} else {
print "NOT_FOUND"
}
The finite collection supplies the bound. Post-loop state distinguishes early success from exhaustion.
4.14 Bounded retry pattern
A retry loop requires a maximum attempt count even when a success flag can end it earlier.
let attempts = 0
let success = false
const max_attempts = 3
while attempts < max_attempts {
attempts += 1
if attempts == 2 {
success = true
break
}
}
Attempts is incremented before the success test, so every entered iteration is counted. The loop can stop because success occurred or because the limit was exhausted.
4.15 Layered defensive termination
- Logical condition: stop when the desired state is reached.
- Iteration bound: stop after a maximum number of attempts or elements.
- Input bound: reject collections or ranges that exceed the approved size.
- Runtime budget: configure instruction, time, memory, output, and other limits at the host boundary.
- Exit evidence: record whether completion, exhaustion, invalid data, or another reason ended processing.
No single layer replaces the others. Program logic explains intended termination; host resource budgets limit damage if that reasoning is wrong.
4.16 Loop-control trace
When tracing break or continue, record the control event explicitly:
| Iteration | State | Control event | Next location |
|---|---|---|---|
| 1 | Value accepted | None | Remaining body |
| 2 | Value rejected | continue | Next iteration |
| 3 | Target found | break | After loop |
4.17 Common mistakes
- Breaking before recording the result: post-loop code cannot explain why the loop stopped.
- Assuming break exits all nested loops: it exits only the nearest loop.
- Assuming continue affects an outer loop: it targets only the nearest loop.
- Skipping a while-loop update: continue can create an infinite loop.
- Skipping required accounting: counters and invariants become inconsistent.
- Using break to hide an incorrect condition: repair the loop design rather than adding an unexplained escape.
- Using many control transfers in one body: the execution path becomes hard to audit.
- Leaving retries unbounded: add attempt and runtime limits.
- Ignoring nested-loop multiplication: bound every dimension.
- Printing unbounded trace output: diagnostics also consume resources.
4.18 Debugging workflow
- Identify the nearest loop for each break or continue.
- Mark the statements skipped by each control transfer.
- Check that required state is recorded before break.
- Check that progress and bookkeeping occur before continue.
- Verify invariants on ordinary, break, and continue paths.
- Trace normal completion, early success, and exhaustion separately.
- Calculate the maximum nested-loop iterations.
- Review host resource limits and output bounds.
4.19 Guided practice
- Trace the first-match search and identify the unvisited values.
- Move a while-loop update so continue cannot skip it.
- Explain which loop a break exits in a two-level nest.
- Explain which iteration continue advances in a nested loop.
- Add a flag that lets an inner match stop both loop levels.
- Calculate the maximum work for ranges of 10 and 20 values.
- Design post-loop output that distinguishes found, not found, and limit exhausted.
- Replace an unexplained break with a clearer loop condition where appropriate.
4.20 Hands-on lab: Build a bounded matrix search
Create matrix_search.pea using a source-defined list of rows, where each row is a list of numeric values. Search for a target value with nested loops.
Requirements:
- Track row and column positions.
- Record the matched value and reason code before leaving a loop.
- Use break to exit the inner loop after a match.
- Use a found flag to exit the outer loop.
- Count inspected cells.
- Define a maximum-cell budget and stop safely if it is reached.
- Print FOUND, NOT_FOUND, or LIMIT_EXHAUSTED with labeled evidence.
- Test a first-cell match, middle match, last-cell match, missing target, empty matrix, and limit exhaustion.
Deliverable: The source file, maximum-work calculation, control-flow trace for every test, expected and actual output, and a short proof that every path terminates.
4.21 Review questions
- What does break do to the nearest loop?
- What does continue skip?
- Why should a match be recorded before break?
- Why can continue be dangerous in a while loop?
- How must a continue path preserve a loop invariant?
- Why does break require post-loop exit evidence?
- Which loop does break target inside nested loops?
- How can a flag stop multiple loop levels?
- How is maximum work calculated for two nested loops?
- What layers contribute to defensive termination?
- How do normal exhaustion, early success, and limit exhaustion differ?
- Why do runtime budgets complement rather than replace correct loop logic?
4.22 Applied challenge
Extend the Chapter 3 score analyzer to skip invalid scores with continue, stop early when a configured critical score is found, and enforce a maximum number of inspected items. Record accepted, skipped, and inspected counts; preserve their invariant; and report whether processing ended normally, on a critical match, or because the limit was exhausted.
Lesson summary
Break leaves the nearest loop, while continue skips the remainder of the nearest loop’s current iteration. Both require explicit reasoning about state, invariants, progress, and exit evidence. Nested loops multiply work and need per-dimension bounds. Safe control flow records results before early exit, performs essential updates before continue, distinguishes completion modes after the loop, and combines logical bounds with host resource budgets.
Lesson status: Approved.