Anatomy of Loops
Loops repeat a block of code, letting a short program process datasets, run until a condition is met, or perform a computation many times.
Every loop needs three components:
- Initialisation: The starting state of the loop.
- Condition: Checked before each pass to decide whether to keep going.
- Update: Progress made toward stopping the loop.
| Loop Type | Best Used For | Condition Check | Formula / Structure |
|---|---|---|---|
| for loop | Known number of repetitions | Over a range or collection | ( iterations) |
| while loop | Unknown number of repetitions | As long as a condition stays true | Checked before every pass |
Failing to provide a proper update causes an infinite loop, where the program runs forever.
Nested Loops & Pitfalls
Loops can be nested (a loop inside a loop). A nested pair over items multiplies the work, performing iterations and creating quadratic running times.
Watch out for these classic bugs:
- Off-by-one errors: Looping one time too many or too few, usually by confusing
<with<=or miscounting start and end points. - Index overflow: Iterating indices
0toninclusive touchesn+1elements, which is one too many for a list of lengthn(indices0ton-1). - Infinite loops: A while loop condition that never becomes false because the update is missing or moves the wrong way.
Always ensure your loop makes genuine progress toward termination to avoid these costly bugs.