Grade 7 Computer Science · What a program is

Why there are several correct solutions

Correctness is not unique — so a further criterion is needed to choose.

Fifty-five, two completely different ways

One program counts from one to ten, adding as it goes. Another does a single calculation and reaches the same answer. Both are correct — so which should you write? The answer depends on a question most beginners never ask.

In school mathematics there is usually one answer. In programming there are many different programs that all give exactly the right result. That is confusing at first, and it is in fact the most interesting thing about the subject.

The criterionWhen it decides
ClarityAlmost always, and especially at the start
SpeedWhen the input is very large
RobustnessWhen the input is not under your control

Two programs, the same result

Here are two ways to add the numbers from one to ten. Both are correct and both return fifty-five. The first goes one by one; the second uses a formula. The second is far faster when the number is large, and the first is clearer to a reader who does not know the formula. Which is correct? Both. Which is right to choose? It depends on the criterion — and that is exactly the point.

total = 0
for i in range(1, 11):
    total = total + i
print(total)
n = 10
print(n * (n + 1) // 2)

Example 1 — why clarity wins at the start

  1. A fast but unclear program breaks in a month.
  2. You do not remember why you wrote it so.
  3. So you cannot fix it without rewriting.
  4. The time saved in running is paid in maintenance.

Example 2 — when speed really matters

  1. On an input of ten items the difference is not measurable.
  2. On an input of a million it is the difference between a second and minutes.
  3. So one first asks how large the input is.
  4. Optimising without that question is guesswork.
Two correct solutions; the criterion — here, the size of the input — decides between them.