# Loops and Iteration

Mathematics I · Programming Elements · https://tryals.app/learn/mathematics-i/loops-and-iteration

## 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 | $\text{for } i = 1 \text{ to } n$ ($n$ 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 $n$ items multiplies the work, performing $n^2$ 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 `0` to `n` inclusive touches `n+1` elements, which is one too many for a list of length `n` (indices `0` to `n-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.

## Practice questions

4 of this lesson's 10 practice questions, with answers. The full set is in the app.

### 1. A `while` loop can express any `for` loop, but some `while` loops cannot be written as a `for` loop.

**Answer:** False

**Why:** False. Both directions hold: a `for` is a `while` with the initialiser, test and update written in one place, and any `while` can be written as a `for` with those slots filled or left empty. The choice is about readability, `for` when the iteration count is known up front, `while` when the stopping condition is discovered as you go.

Page: https://tryals.app/practice/mathematics-i/loops-and-iteration/a-while-loop-can-express-any-for-loop-but-some-while-loops-cannot-be

### 2. Order what a loop does, from entry to the start of its second pass.

**Answer:**

1. Initialise the counter
2. Test the condition
3. Run the loop body
4. Update the counter
5. Test the condition again

**Why:** Initialisation, condition, body, update, condition, the three ingredients in their natural cycle. If the update is missing or moves the wrong way, the second test gives the same verdict as the first and the loop never ends.

Page: https://tryals.app/practice/mathematics-i/loops-and-iteration/order-what-a-loop-does-from-entry-to-the-start-of-its-second-pass

### 3. A `while` loop whose condition never becomes false runs forever. Why is proving termination genuinely harder than it sounds?

A. Because while loops are inherently less predictable than for loops
B. Because termination depends on the machine's speed
C. Because it needs a quantity that strictly decreases toward a bound
D. Because compilers cannot analyse loop conditions

**Answer:** C. Because it needs a quantity that strictly decreases toward a bound

**Why:** Termination needs a decreasing measure bounded below, the same shape as an induction argument. And no general algorithm can settle it: Turing proved the halting problem undecidable, which is why compilers warn about suspicious loops rather than proving them safe.

Page: https://tryals.app/practice/mathematics-i/loops-and-iteration/a-while-loop-whose-condition-never-becomes-false-runs-forever-why-is

### 4. A loop runs: i = 10; while i > 0 do { print i; i = i - 3 }. Select every value that gets printed.

A. 0
B. 7
C. 1
D. 4
E. 10
F. -2

**Answer:** B. 7; C. 1; D. 4; E. 10

**Why:** 10, 7, 4 and 1 are printed; i then becomes -2, the test i > 0 fails and the loop ends before printing again. Because the counter steps by 3 it never lands on 0, a condition of 'i is not 0' would have looped forever.

Page: https://tryals.app/practice/mathematics-i/loops-and-iteration/a-loop-runs-i-10-while-i-0-do-print-i-i-i-3-select
