Loops & Iteration Control
Exhaustive exploration of conditional while loops, deterministic range generators, iterator protocols, termination proofs, and nested loop Big-O complexity.
1. The While Loop State Machine
A while loop is a conditional repetition construct governed by a boolean predicate. Before every iteration, the CPU evaluates the condition register. If true, the loop body executes and mutates state; if false, execution immediately branches to the post-loop instruction address.
+-----------------------+
| Evaluate Predicate P |<-------------+
+-----------------------+ |
| |
[True] v [False] |
+------------------+ +----------+ |
| Execute Body & | | Terminate| |
| Mutate State | | & Branch | |
+------------------+ +----------+ |
| |
+--------------------------+
The Three Pillars of Loop Correctness:
- Initialization: The state variables must be valid prior to the first predicate check.
- Maintenance (Invariant): Each execution step must preserve algorithmic correctness while driving variables monotonically toward the termination threshold.
- Termination: The predicate must eventually evaluate to false, proving that the loop does not run indefinitely.
1def reverse_integer_digits(n: int) -> int:2 """Reverses digits of an integer using while loop state reduction."""3 reversed_val = 04 current = abs(n)56 while current > 0:7 digit = current % 10 # Extract least significant digit8 reversed_val = (reversed_val * 10) + digit9 current = current // 10 # State reduction: strictly decreasing1011 return -reversed_val if n < 0 else reversed_val1213# Verification14val = 984215print(f'Original: {val} -> Reversed: {reverse_integer_digits(val)}')
Original: 9842 -> Reversed: 2489
2. Proving Termination with Monotonic Decrease
To guarantee that a while loop does not form an infinite execution freeze, every engineer must identify the Loop Variant Function V(state) -> Integer.
If V(state) is bounded from below (e.g., V >= 0) and strictly decreases on every iteration (V_{k+1} < V_k), termination is mathematically proven by the Well-Ordering Principle.
Loop Invariant vs Loop Variant Comparison
| Concept | Mathematical Role | Must Hold At | Purpose |
|---|---|---|---|
| Loop Invariant | Predicate P(k) that evaluates to True | Before and after every iteration | Proves correct partial output |
| Loop Variant | Non-negative integer metric V(k) | Decreases: V(k+1) < V(k) | Proves that the loop terminates |
Quick Syntax & Reference Sheet
| Concept / Rule | Syntax / Usage |
|---|---|
| While Loop Template | while predicate:
# body
# state update |
| Two-Pointer Convergence | while left < right:
# process and adjust left += 1 or right -= 1 |
Common Pitfalls & Developer Mistakes
Forgetting the State Mutation Step
Why it happens:
Off-By-One Boundary Error (`<` vs `<=`)
Why it happens: