PeaBox Lab › PeaLang › Learn › Chapter 3 › Lesson 4

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:

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 modeEvidence
Normal exhaustionNo match or stop flag was recorded
Early successFound value or success flag is present
Defensive limitAttempt counter reached its maximum
Invalid stateError 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

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:

IterationStateControl eventNext location
1Value acceptedNoneRemaining body
2Value rejectedcontinueNext iteration
3Target foundbreakAfter loop

4.17 Common mistakes

4.18 Debugging workflow

4.19 Guided practice

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:

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

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.

← Previous Next →