Study Guide

Totalling, Counting and Finding Extremes

The standard methods programs use over and over: keeping a running total, counting how many times something happens, finding the highest and lowest values, and working out an average, each built from a loop and an IF.

Lesson 5.6 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who have met loops and selection (about ages 13 to 14)

Stage: Think

A long list of marks

The pupils of Class 9B (a fictional class) sit a test marked out of 20. The teacher has a long list of marks and wants to know the total, the average, the highest mark, the lowest mark and how many pupils passed. She has a calculator and a pencil, and the marks are read out one at a time, so she cannot see the whole list at once.

Think it through

Describe how she could find the highest mark and the average while the marks are read out one at a time. What does she have to keep track of between one mark and the next?

Show a model answer

For the average she keeps a running total of the marks so far, and a count of how many marks she has heard. At the end she divides the total by the count. For the highest she remembers the highest mark so far, and when a new mark is higher she replaces it. A program has to keep track in just the same way, with a variable for each thing remembered.

Stage: Predict

Keeping a running total

Totalling means adding each value to a running total. A fictional quiz has four rounds, and the program adds up the points from each round.

Total ← 0
FOR Round ← 1 TO 4
  INPUT Score
  Total ← Total + Score
NEXT Round
OUTPUT Total

Think it through

A team scores 3, 5, 2 and 6 in the four rounds. Predict what the program outputs. Then say why the first line is needed.

Show a model answer

It outputs 16 (3 + 5 + 2 + 6). The first line sets Total to 0 before any score has been added. Without it Total would hold nothing meaningful on the first pass, so the first Total ← Total + Score would have nothing sensible to add the score to.

Totalling always has the same shape: set the total to 0 before the loop, and inside the loop add each new value to it. Trace it:

Following the quiz total
RoundScore typedTotal after the round
13
25
32
46

    Show the completed table
    RoundScore typedTotal after the round
    133
    258
    3210
    4616

    After the loop, OUTPUT Total shows 16.

    Set the total to 0 outside the loop, before it starts. If Total ← 0 is moved inside the loop, think about what Total holds at the start of each pass, and what that does to the running total.

    Apply it

    A programmer moves Total ← 0 to be the first line inside the loop, before INPUT Score. The scores are 3, 5, 2 and 6 again. What does OUTPUT Total show after the loop?
    Show the answer

    Answer: C. 6, because Total is reset every time, so only the last score is added.

    A total that is reset on every pass cannot grow.

    Stage: Discover

    Counting how many

    Class 9B’s teacher now wants to know how many of five pupils passed. A mark of 50 or more is a pass. Five marks are read out: 62, 45, 50, 38 and 71.

    Think it through

    How many passed, and how did you keep track as you went along? What is the difference between how you kept track here and in the running total?

    Show a model answer

    Three passed: 62, 50 and 71. A tally goes up by exactly one for each pass, and nothing happens for a mark below 50. In the running total, each new value was added; here, 1 is added for each mark that meets the condition.

    Counting means adding 1 to a variable each time something happens. It is a total where each thing counts as 1, and it is usually inside an IF, so that only the values that meet a condition are counted.

    Passes ← 0
    FOR Pupil ← 1 TO 5
      INPUT Mark
      IF Mark >= 50
        THEN
          Passes ← Passes + 1
      ENDIF
    NEXT Pupil
    OUTPUT Passes
    Following the pass count
    PupilMark typedMark >= 50?Passes after the pupil
    162
    245
    350
    438
    571

      Show the completed table
      PupilMark typedMark >= 50?Passes after the pupil
      162Yes1
      245No1
      350Yes2
      438No2
      571Yes3

      Do not confuse: Totalling and counting

      What is added?Totalling
      The value itself is added to the running total.Total ← Total + Mark
      What is added?Counting
      The number 1 is added to the counter each time something happens.Passes ← Passes + 1

      Both start at 0, set before the loop. A total answers “how much altogether?”; a count answers “how many?”.

      Check your understanding

      The mark 50 is read out. The teacher says it is a pass. Which condition counts it?
      Show the answer

      Answer: A. Mark >= 50

      Check the boundary value when choosing between > and >=.

      Stage: Discover

      Remembering the highest and lowest

      A fictional weather station records the temperature at noon on five days: 12, 7, 15, 9 and 13 degrees. The numbers are read one at a time, and each is forgotten once it has been dealt with.

      Think it through

      You are remembering the highest so far. What value would you start with before the first temperature arrives? Does 0 work? Does 0 work for remembering the lowest?

      Show a model answer

      Starting with 0 for the highest works only if no value can be below 0: on a freezing week where every temperature is negative, the program would report 0, which never happened. Starting with 0 for the lowest is wrong for these values, because no positive temperature is ever lower than 0. The safest start is the first value itself, as it is the highest and the lowest so far.

      To find the highest (maximum) and lowest (minimum) values, remember the best so far and replace it whenever a better one arrives. Start both with the first value, and then deal with the rest:

      INPUT Reading
      Highest ← Reading
      Lowest ← Reading
      FOR Day ← 2 TO 5
        INPUT Reading
        IF Reading > Highest
          THEN
            Highest ← Reading
        ENDIF
        IF Reading < Lowest
          THEN
            Lowest ← Reading
        ENDIF
      NEXT Day
      OUTPUT "Highest: ", Highest
      OUTPUT "Lowest: ", Lowest

      The loop starts at Day 2, because Day 1’s reading has already been read before the loop. Trace the five readings:

      Following the highest and lowest
      DayReadingHighestLowest
      1121212
      27
      315
      49
      513

        Show the completed table
        DayReadingHighestLowest
        1121212
        27127
        315157
        49157
        513157

        The program outputs Highest: 15 and Lowest: 7.

        Setting the starting values for both Highest and Lowest to 0 is a common mistake. Test it on a list of positive numbers and look at what Lowest ends up as. Starting with the first value is safe for any numbers. Starting Highest at 0 is only right when no value can be negative, as with marks or rainfall.

        Check your understanding

        A programmer sets Lowest ← 0 before the loop, then runs the loop above for the readings 12, 7, 15, 9 and 13. What does the program output for Lowest?
        Show the answer

        Answer: C. 0, because no reading is below the starting value, so Lowest is never replaced.

        The starting value of a maximum or minimum must come from the data.

        Stage: Explain

        Putting it together: the average

        The average (mean) of some values is their total divided by how many there are. So it needs both a running total and a count. Class 9B’s marks are being read out, and nobody knows how many pupils there are. The teacher says “-1” at the end.

        Think it through

        For the marks 12, 7, 15, 9 and 13, work out the average by hand. Which two quantities did you need, and could you work it out before the last mark had been read?

        Show a model answer

        The marks add up to 56 and there are 5 of them, so the average is 56 divided by 5 = 11.2. You need the total and the count, and you cannot work out the average until the last mark has been read, because both the total and the count are still changing until then.

        1. Decide what must be remembered. A running total and a count of marks. Both start at 0, and both must be set before the loop (otherwise they would be reset on every pass).
        2. Choose the loop. The number of marks is not known in advance, and the user might type -1 straight away, so a pre-condition WHILE loop is used, with the first mark read before it and the next mark read at the end of each pass.
        3. Inside the loop. Add the mark to Total and add 1 to Count. The -1 is never added, because the loop stops as soon as it is read.
        4. After the loop. Divide Total by Count, once all the marks have been read. Doing it inside the loop would give a half-finished answer on every pass.
        5. Guard the division. If no marks were entered, Count is 0 and dividing by it is impossible, so check Count > 0 first.
        Total ← 0
        Count ← 0
        INPUT Mark
        WHILE Mark <> -1 DO
          Total ← Total + Mark
          Count ← Count + 1
          INPUT Mark
        ENDWHILE
        IF Count > 0
          THEN
            OUTPUT Total / Count
          ELSE
            OUTPUT "No marks entered"
        ENDIF

        For 12, 7, 15, 9, 13, -1: Total reaches 56, Count reaches 5, and the program outputs 11.2.

        Check your understanding

        Why is the division Total / Count placed after ENDWHILE and not inside the loop?
        Show the answer

        Answer: A. Because Total and Count are only complete once every mark has been read.

        Work out a result only when everything it depends on is complete.

        Stage: Apply

        All the methods in one program

        Here is the fuller program for Class 9B: it totals, counts, averages and finds the highest and lowest marks. Marks are out of 20 and -1 ends the list.

        Total ← 0
        Count ← 0
        INPUT Mark
        Highest ← Mark
        Lowest ← Mark
        WHILE Mark <> -1 DO
          Total ← Total + Mark
          Count ← Count + 1
          IF Mark > Highest
            THEN
              Highest ← Mark
          ENDIF
          IF Mark < Lowest
            THEN
              Lowest ← Mark
          ENDIF
          INPUT Mark
        ENDWHILE
        IF Count > 0
          THEN
            OUTPUT "Marks: ", Count
            OUTPUT "Total: ", Total
            OUTPUT "Average: ", Total / Count
            OUTPUT "Highest: ", Highest
            OUTPUT "Lowest: ", Lowest
          ELSE
            OUTPUT "No marks entered"
        ENDIF

        The marks typed are 12, 7, 15, 9, 13 and then -1. Each row shows the variables after the loop body has dealt with that mark.

        Following the fuller program: one row for each mark
        Mark dealt withTotalCountHighestLowest
        12
        7
        15
        9
        13

          Show the completed table
          Mark dealt withTotalCountHighestLowest
          121211212
          7192127
          15343157
          9434157
          13565157

          Then -1 is read, the loop stops, and the program outputs Marks: 5, Total: 56, Average: 11.2, Highest: 15 and Lowest: 7.

          Sam (fictional) writes a version for a different class, and runs it on the same marks: 12, 7, 15, 9, 13, -1. It outputs “Total: 5”.

          Total ← 0
          Count ← 0
          INPUT Mark
          WHILE Mark <> -1 DO
            Total ← Total + 1
            Count ← Count + 1
            INPUT Mark
          ENDWHILE
          OUTPUT "Total: ", Total

          Apply it

          Why does Sam’s program output a total of 5 instead of 56?
          Show the answer

          Answer: B. It adds 1 to Total each time instead of Mark, so Total works as a count.

          Totalling adds the value; counting adds 1. Mixing them up is a common slip.

          Stage: Apply

          Write one yourself

          A fictional weather station records the rainfall in millimetres on each of seven days, as whole numbers that are never negative.

          Think it through

          Write pseudocode that inputs the seven readings and outputs the total rainfall, the number of days on which it rained (a reading above 0) and the highest reading. Say what you start the highest reading with and why that is safe here.

          Show a model answer
          Total ← 0
          RainyDays ← 0
          Highest ← 0
          FOR Day ← 1 TO 7
            INPUT Rainfall
            Total ← Total + Rainfall
            IF Rainfall > 0
              THEN
                RainyDays ← RainyDays + 1
            ENDIF
            IF Rainfall > Highest
              THEN
                Highest ← Rainfall
            ENDIF
          NEXT Day
          OUTPUT "Total rainfall: ", Total
          OUTPUT "Rainy days: ", RainyDays
          OUTPUT "Highest: ", Highest

          A FOR loop is used because there are exactly seven readings. Highest can start at 0 because no reading can be below 0, so the first reading is never lost; for values that may be negative, start with the first value instead. Total and RainyDays are set before the loop.

          Go deeper The same ideas in Python
          total = 0
          count = 0
          mark = int(input())
          highest = mark
          lowest = mark
          while mark != -1:
              total = total + mark
              count = count + 1
              if mark > highest:
                  highest = mark
              if mark < lowest:
                  lowest = mark
              mark = int(input())
          if count > 0:
              print("Average:", total / count)
          else:
              print("No marks entered")
          • Python has built-in sum, max, min and len that work on a list, so a real program might use them. The exam asks for the loop, because the method is the point, so practise that way.
          • total / count always gives a real number in Python (56 / 5 is 11.2, and 10 / 5 is 2.0).
          • != is “not equal to”, and += is a short way to write the update: total += mark means total = total + mark.

          Stage: Consolidate

          Show what you know

          Think it through

          Explain to a friend how to tell a total, a count and a maximum apart, using the same list of marks. Say where each starting value is set and what it is.

          Show a model answer

          A good answer uses the same marks for all three. A total adds each mark itself, starting at 0 before the loop. A count adds 1 for each mark that meets a condition (or each mark at all), starting at 0 before the loop. A maximum remembers the highest so far and replaces it when a bigger mark arrives, starting with the first mark (or 0 only if no mark can be negative). Each starting value is set before the loop, never inside it.

          Apply it

          A fictional library wants the average number of books borrowed per pupil on a day, from a list of 30 pupils’ counts. The number of pupils is always exactly 30. Which description of the algorithm is best?
          Show the answer

          Answer: A. A FOR loop of 30 passes, adding each count to Total, then dividing Total by 30 after the loop.

          Set starting values before a loop, update inside it, and calculate the result afterwards.

          • Totalling: set the total to 0 before the loop; inside the loop, add each value to it: Total ← Total + Value.
          • Counting: set the counter to 0 before the loop; add 1 each time something happens, usually inside an IF: Count ← Count + 1.
          • Highest and lowest: start with the first value (or a value that no data can beat), and replace it when a better one arrives. Starting the lowest at 0 is a common mistake.
          • Average: total divided by count, worked out after the loop, and only if the count is above 0.
          • The usual faults are resetting a total inside a loop, adding 1 where the value was needed, starting an extreme at the wrong value and calculating the average too early.

          Sources and scope

          • What this lesson is. The sixth lesson of the Algorithms and Programming module, written for this site. It covers point 8.1.4(d) and the totalling, counting, maximum, minimum and average methods of point 7.4 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6). Its curriculum links are provisional and imply no review or endorsement by any examination board.
          • Original material. Class 9B, the quiz, the weather station, the library and Sam are fictional, written for this lesson. The pseudocode follows the layout in the syllabus’s pseudocode guide, and each program’s output was worked out by hand.
          • Simplified on purpose. The programs assume the user types sensible numbers (validation is left to a later lesson); -1 is used to end a list because it is not a valid mark. Averages are shown with a fractional part; rounding (the ROUND routine) is not taught here.
          • Left to later lessons. Linear search and bubble sort, the other standard methods in point 7.4, validation and verification, and the choice of test data.