Skip to the page
Year 10 Β· Computer Science Β· Spring 2 Β· Algorithm design and problem solving

Standard methods: totals, counts, max, min, average

What this lesson covers

7.4 Standard methods of solution

Cambridge IGCSE Computer Science 0478 Β· Topic 7: Algorithm design and problem-solving Β· Paper 2

You will learn to

  • Write totalling and counting in pseudocode and in Python.
  • Write an algorithm to find the maximum, minimum and average of a set of values.
  • Explain why the starting values of the total, maximum and minimum matter.

Success criteria

  • I can write a total and a count from memory, in both languages.
  • I can find the biggest value with a loop, and check it in the trace toy.
  • I can explain why the maximum should start at the first value, not at 0.
The syllabus points for this section
  • Write totalling and counting in pseudocode and Python.
  • Find the maximum, minimum and average of a set of values.
  • Write and trace a linear search.
  • Write and trace a bubble sort.
  • Count the comparisons a bubble sort makes.

Key words

Say each word, then read what it means. Every one is in the glossary too.

Program development life cycle
The four stages of making a program: analysis, design, coding and testing.
Pseudocode
A structured, code-like way of writing an algorithm that is not tied to one language.
Totalling
Adding values into a running total, for example Total ← Total + Value.
Counting
Adding 1 to a counter each time something happens.
Linear search
Checking each item in a list in turn until the target is found or the list ends.
Bubble sort
Sorting by comparing neighbouring items and swapping them if they are in the wrong order, pass after pass.
Check digit
An extra digit calculated from the other digits, used to catch typing errors.
Trace table
A table used in a dry run to record the value of each variable as an algorithm runs.

The explanation

Read it here, or open the study page below to go one step at a time with things to try.

Totalling and counting

Totalling means adding values into a running total: `Total ← Total + Value`.

Counting means adding 1 each time something happens: `Count ← Count + 1`.

Both variables must start at 0 before the loop.

e.g.Example
Marks 34, 48, 21, 40, 15, 45. Pass mark 25. Total: 0 β†’ 34 β†’ 82 β†’ 103 β†’ 143 β†’ 158 β†’ 203 PassCount: 34 yes (1), 48 yes (2), 21 no, 40 yes (3), 15 no, 45 yes (4) Output: Total: 203, Number of passes: 4
DECLARE Marks : ARRAY[1:6] OF INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
DECLARE PassCount : INTEGER
// Marks already holds 34, 48, 21, 40, 15, 45
Total ← 0
PassCount ← 0
FOR Index ← 1 TO 6
  Total ← Total + Marks[Index]
  IF Marks[Index] >= 25
    THEN
      PassCount ← PassCount + 1
  ENDIF
NEXT Index
OUTPUT "Total: ", Total
OUTPUT "Number of passes: ", PassCount
marks = [34, 48, 21, 40, 15, 45]
total = 0
pass_count = 0
for index in range(6):
    total = total + marks[index]
    if marks[index] >= 25:
        pass_count = pass_count + 1
print("Total:", total)
print("Number of passes:", pass_count)
!Watch out

Setting Total to 0 inside the loop is a classic error. The total is wiped each time round, so only the last value is kept.

Finding the maximum and minimum

To find the maximum (largest), keep a variable `Highest`. Compare each value with it. If the value is bigger, it becomes the new `Highest`.

The minimum (smallest) works the same way with `Lowest` and `<`.

Start `Highest` at the smallest possible value and `Lowest` at the largest possible value. Another safe way is to start both at the first item.

e.g.Example
Marks out of 50: 34, 48, 21, 40, 15, 45. Highest: 0 β†’ 34 β†’ 48 (21, 40, 15, 45 are not bigger than 48) Lowest: 50 β†’ 34 β†’ 21 β†’ 15 (40, 45 are not smaller than 15) Output: Highest: 48, Lowest: 15
DECLARE Marks : ARRAY[1:6] OF INTEGER
DECLARE Index : INTEGER
DECLARE Highest : INTEGER
DECLARE Lowest : INTEGER
// Marks already holds 34, 48, 21, 40, 15, 45 (each out of 50)
Highest ← 0
Lowest ← 50
FOR Index ← 1 TO 6
  IF Marks[Index] > Highest
    THEN
      Highest ← Marks[Index]
  ENDIF
  IF Marks[Index] < Lowest
    THEN
      Lowest ← Marks[Index]
  ENDIF
NEXT Index
OUTPUT "Highest: ", Highest
OUTPUT "Lowest: ", Lowest
marks = [34, 48, 21, 40, 15, 45]
highest = 0
lowest = 50
for index in range(6):
    if marks[index] > highest:
        highest = marks[index]
    if marks[index] < lowest:
        lowest = marks[index]
print("Highest:", highest)
print("Lowest:", lowest)
!Watch out

If Lowest starts at 0, no mark is ever smaller, so the answer is wrong. Start Lowest at the top of the range (50 here) or at the first value.

Finding the average

The average (mean) is the total divided by how many values there are.

First total the values in a loop. Then divide once, after the loop.

The answer is usually not a whole number, so store it as `REAL`. Use `ROUND` to give a set number of decimal places.

e.g.Example
Marks 34, 48, 21, 40, 15, 45. Total = 203. Count = 6. Average = 203 Γ· 6 = 33.8333… Rounded to 2 decimal places: 33.83
DECLARE Marks : ARRAY[1:6] OF INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
DECLARE Average : REAL
// Marks already holds 34, 48, 21, 40, 15, 45
Total ← 0
FOR Index ← 1 TO 6
  Total ← Total + Marks[Index]
NEXT Index
Average ← Total / 6
OUTPUT "Average: ", ROUND(Average, 2)
marks = [34, 48, 21, 40, 15, 45]
total = 0
for index in range(6):
    total = total + marks[index]
average = total / 6
print("Average:", round(average, 2))
!Watch out

Do not divide inside the loop. Also check the count is not 0 before dividing, or the program crashes.

Linear search

A linear search looks for a value by checking each item in a list, one at a time, from the start.

It stops when it finds the item, or when it reaches the end of the list.

Try it: the toy's list holds numbers, not names. Type 22 (the last item), press Search for it, then Run all. Then try 99, which is not there. Count the comparisons each time.

e.g.Example
List: Lucia, Hugo, Martina, Pablo, Sofia, Leo. Target: Pablo. Position 1: Lucia β‰  Pablo Position 2: Hugo β‰  Pablo Position 3: Martina β‰  Pablo Position 4: Pablo = Pablo β†’ Found ← TRUE Output: Pablo found at position 4 (4 comparisons) Target Ana: all 6 compared, none match β†’ Ana is not in the list
DECLARE Names : ARRAY[1:6] OF STRING
DECLARE Target : STRING
DECLARE Index : INTEGER
DECLARE Found : BOOLEAN
// Names already holds Lucia, Hugo, Martina, Pablo, Sofia, Leo
OUTPUT "Which name do you want to find? "
INPUT Target
Found ← FALSE
Index ← 1
WHILE Found = FALSE AND Index <= 6 DO
  IF Names[Index] = Target
    THEN
      Found ← TRUE
    ELSE
      Index ← Index + 1
  ENDIF
ENDWHILE
IF Found = TRUE
  THEN
    OUTPUT Target, " found at position ", Index
  ELSE
    OUTPUT Target, " is not in the list"
ENDIF
names = ["Lucia", "Hugo", "Martina", "Pablo", "Sofia", "Leo"]
target = input("Which name do you want to find? ")
found = False
index = 0
while found == False and index < 6:
    if names[index] == target:
        found = True
    else:
        index = index + 1
if found == True:
    print(target, "found at position", index + 1)
else:
    print(target, "is not in the list")
?Why?

A linear search works on any list, sorted or not. The cost is time: a list of 1000 names can need 1000 comparisons.

!Watch out

The `Found` flag stops the loop early. Without it the search carries on to the end even after the name is found.

There is something to try for this step in the IGCSE library.

Bubble sort

A bubble sort puts a list in order. It compares each pair of neighbours. If they are in the wrong order, it swaps them.

One trip through the list is a pass. After each pass the largest unsorted value has 'bubbled' to the end.

It stops when a pass makes no swaps. The toy uses a longer list: 6, 2, 9, 4, 7, 1, 5. Press Reset, then Step one comparison at a time. Watch the 9 move to the end in pass 1.

PassList after the passComparisonsSwaps
Start7, 3, 9, 2, 5
13, 7, 2, 5, 943
23, 2, 5, 7, 932
32, 3, 5, 7, 921
42, 3, 5, 7, 910 β†’ stop
DECLARE Numbers : ARRAY[1:5] OF INTEGER
DECLARE Top : INTEGER
DECLARE Index : INTEGER
DECLARE Temp : INTEGER
DECLARE Swap : BOOLEAN
Numbers[1] ← 7
Numbers[2] ← 3
Numbers[3] ← 9
Numbers[4] ← 2
Numbers[5] ← 5
Top ← 5
REPEAT
  Swap ← FALSE
  FOR Index ← 1 TO Top - 1
    IF Numbers[Index] > Numbers[Index + 1]
      THEN
        Temp ← Numbers[Index]
        Numbers[Index] ← Numbers[Index + 1]
        Numbers[Index + 1] ← Temp
        Swap ← TRUE
    ENDIF
  NEXT Index
  Top ← Top - 1
UNTIL Swap = FALSE OR Top = 1
# Python has no REPEAT ... UNTIL, so a WHILE loop is used
numbers = [7, 3, 9, 2, 5]
top = 5
swap = True
while swap == True and top > 1:
    swap = False
    for index in range(top - 1):
        if numbers[index] > numbers[index + 1]:
            temp = numbers[index]
            numbers[index] = numbers[index + 1]
            numbers[index + 1] = temp
            swap = True
    top = top - 1
print(numbers)
?Why?

The swap uses `Temp` because `A ← B` then `B ← A` would lose A's value. `Temp` keeps a copy. `Top` goes down by 1 each pass because the end of the list is already sorted.

!Watch out

The loop runs to `Top - 1`, not `Top`. The last comparison is item `Top - 1` with item `Top`. Going to `Top` would compare with an item past the end.

There is something to try for this step in the IGCSE library.

How many comparisons? (extra)

This formula is not in the syllabus. It is useful for understanding why bubble sort is slow for long lists.

In the worst case every pass is needed. With n items, pass 1 makes n βˆ’ 1 comparisons, pass 2 makes n βˆ’ 2, and so on down to 1.

Adding these gives n(n βˆ’ 1) Γ· 2. Double the list and the work goes up about four times.

e.g.Example
n = 5: (5 Γ— 4) Γ· 2 = 10 comparisons. Check: 4 + 3 + 2 + 1 = 10. This matches the table above. n = 30 (a class): (30 Γ— 29) Γ· 2 = 435 n = 1000: (1000 Γ— 999) Γ· 2 = 499 500
?Why?

This shows why a sort that is fine for a class list is too slow for a million customers. Faster sorts exist, but they are not in this course.

Study it

Open the study page and go one step at a time.

The steps for this lesson

Try it

Check yourself

One question at a time. The reason shows after each answer.

Saved on this device.