Unit 1 · Basics of Computer Programming

1.1.3Worked examples

On this page
  1. Worked example 1: Average of three numbers (sequence)
  2. Worked example 2: Largest of two numbers (selection)
  3. Worked example 3: Sum of 1 to N (iteration)

Worked example 1: Average of three numbers (sequence)

  1. Start.
  2. Read the numbers a, b and c.
  3. Add them and divide the sum by 3.
  4. Display the average.
  5. Stop.

Why it works: this is pure sequence: every step runs once, in order. Try it with 70, 80 and 90: the sum is 240 and 240 ÷ 3 = 80. Note that the steps must stay in this order: you cannot add the numbers before you have read them.

Worked example 2: Largest of two numbers (selection)

  1. Start.
  2. Read a and b.
  3. If a is greater than b, the largest is a; otherwise the largest is b.
  4. Display the largest.
  5. Stop.

Why it works: the condition "a is greater than b" has two answers, so there are two paths, and exactly one of them runs. Test both paths: with a = 9 and b = 4 the Yes path gives 9; with a = 3 and b = 7 the No path gives 7. What if a and b are equal, say 5 and 5? The condition is false, so the largest is b, which is 5. That is still correct, so the algorithm handles equal values too. Always ask yourself what happens at the edges like this.

Worked example 3: Sum of 1 to N (iteration)

  1. Start.
  2. Read N.
  3. Set total to 0 and i to 1.
  4. While i is less than or equal to N: add i to total, then add 1 to i.
  5. Display total.
  6. Stop.

These algorithms appear again as flowcharts in 1.2.2 and as pseudocode in 1.3.2, so you can compare the three ways of writing the same steps.

Why it works: total collects (accumulates) the running sum and i counts from 1 up to N. Each pass adds the current i and then moves i one step on, so the loop is sure to stop once i passes N. With N = 3: the total goes 0, 1, 3, 6, and then i becomes 4, the condition is false and 6 is displayed.

A variable such as total that starts at 0 and has values added to it in a loop is called an accumulator. A variable such as i that goes up by 1 each pass is called a counter. You will use these two patterns in almost every program.

Worked example 4: Count the passes (iteration with selection)

Problem: read the marks of 5 students and count how many passed (50 or more).

  1. Start.
  2. Set count to 0 and i to 1.
  3. While i is less than or equal to 5: read marks; if marks is 50 or more, add 1 to count; add 1 to i.
  4. Display count.
  5. Stop.

This example nests a selection inside an iteration. With the marks 45, 72, 50, 30 and 88 the count goes 0, 1, 2, 2, 3, so the output is 3. The mark 50 is counted because the rule is "50 or more".