Repeating Steps
Loops repeat a block of code, letting a short program do a large amount of work. They are how algorithms process every element of a dataset, run until a condition is met, or perform a computation many times. Two kinds dominate:
- A for loop repeats a known number of times, typically iterating over a range or a collection ("for each item, do..."). Best when the count is fixed in advance.
- A while loop repeats as long as a condition stays true, checking the condition before each pass. Best when the number of repetitions is not known ahead of time (loop until convergence, until input runs out).
Every loop needs three things to behave: an initialisation (starting state), a condition (when to keep going), and an update (progress toward stopping). If the update never makes the condition false, you get an infinite loop — the program runs forever. Ensuring the loop makes progress toward termination is essential.
Two classic bugs deserve naming:
- Off-by-one errors — looping one time too many or too few, usually from confusing
<with<=or miscounting the start/end. Iterating indices0ton(inclusive) touchesn+1elements, one too many for a list of lengthn. - Infinite loops — a while condition that never becomes false because the update is missing or wrong.
Loops can be nested (a loop inside a loop), which multiplies the work — a nested pair over items does iterations, the source of quadratic running times. Understanding loops is understanding how repetition turns simple instructions into powerful computation, and how their structure determines efficiency.
Common pitfall: the off-by-one error and the infinite loop. Looping from0toninclusive processesn+1items — one too many when a list hasnelements (indices0ton-1); mixing up<and<=is the usual cause. And a while loop whose condition never becomes false — because the update is missing or moves the wrong way — runs forever. Always ensure the loop makes genuine progress toward stopping.
A loop drawn as a circular arrow with an accent counter incrementing each pass and a boundary check that exits when the condition fails — iteration with a termination guard.