Courses / Mathematics I
Programming Elements

Loops and Iteration

Mathematics I 271 words Free to read

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:

Loop TypeBest Used ForCondition CheckFormula / Structure
for loopKnown number of repetitionsOver a range or collectionfor i=1 to n\text{for } i = 1 \text{ to } n (nn iterations)
while loopUnknown number of repetitionsAs long as a condition stays trueChecked 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 nn items multiplies the work, performing n2n^2 iterations and creating quadratic running times.

Watch out for these classic bugs:

Always ensure your loop makes genuine progress toward termination to avoid these costly bugs.

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

Programming Elements