Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

20 min

Why We Need Loops

Recognize repeated work and define an accumulator

By the end of this lesson

  • Recognize repeated work and define an accumulator
  • State what remains true after each repetition

Look for the repeated action

A customer adds three identical 20-unit items to a basket. We could add 20 three times. What information determines how many repetitions are needed? What should the running total mean after each item?

After each processed item, the total should equal the cost of all items processed so far. This is an invariant: a statement that should remain true while the process advances.

let total = 0;
total = total + 20;
total = total + 20;
total = total + 20;
console.assert(total === 60);

This works for exactly three items but duplicates the action. An accumulator holds a running result. Start this sum at 0 because before processing any items, the total is zero.

Design the repetition without syntax

Write: begin with total zero and zero items processed; while fewer than the requested items have been processed, add one unit price and count that item. Stop when the processed count equals the requested quantity. A loop is syntax for this repeated decision and action.

For identical prices, multiplication is simpler. We use repeated addition here to understand the mechanism, not to claim that every calculation needs a loop. Later, differing prices will make iteration useful.

Guided trace

For quantity 3, write the pairs (processed count, total): (0, 0), (1, 20), (2, 40), (3, 60). Resetting total to 0 during each repetition would destroy the accumulated result.

Independent exercise

A routine reviews four forms and counts the reviewed forms. Write its start value, repeated action and stopping rule. What result should it produce for zero forms?

Correction

Start at zero, increment the reviewed count once per form, stop after four. For zero forms, perform no repetitions and return zero. "Do it until finished" is too vague unless finished has a measurable condition.

Review

Before writing any loop, identify its initial state, progress step and stopping condition. If you cannot explain how it stops, the algorithm is not ready for execution.

Lesson complete?

Your progress is saved on this device.