Courses / Mathematics I
Programming Elements

Loops and Iteration

Mathematics I 387 words Free to read

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:

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:

Loops can be nested (a loop inside a loop), which multiplies the work — a nested pair over nn items does n2n^2 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 from 0 to n inclusive processes n+1 items — one too many when a list has n elements (indices 0 to n-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.

for i=1 to n: n iterations\text{for } i = 1 \text{ to } n:\ n \text{ iterations}

Loops and Iteration

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

10practice questions
2interactive scenes
Start Mathematics I free

Programming Elements