CIE IGCSE | 7.4.3 Totalling and Counting

Lesson objective

Distinguish running totals from counters, initialise them correctly and use unconditional and conditional updates in precise algorithms.

Learn

7.4.3 | TOTALLING AND COUNTING

01 | TWO QUESTIONS, TWO DIFFERENT ANSWERS

Three students donate 4, 7 and 2 units to a charity collection. How much was donated? Add the amounts: 4 + 7 + 2 = 13. How many donations were made? Count the donations: 3.

Totalling adds values to obtain their sum. Counting records how many items or events occur, often subject to a condition.

Both can use a value that begins at zero and changes inside a loop. That similarity can be confusing until you inspect what is added: a total usually adds an amount, while a simple counter adds one per occurrence.

This lesson follows those updates carefully. You do not need to memorise two mysterious formulas: understand what the stored value represents before and after each input.

02 | A VARIABLE REMEMBERS WHAT HAS HAPPENED SO FAR

A variable is a named place for a value used by the algorithm. Its current value can change as instructions execute.

Imagine a paper tally sheet. Before any donations arrive, the accumulated amount is zero. After receiving 4, write 4. After receiving 7, replace 4 with 11. After receiving 2, replace 11 with 13.

A running total does this in a program. It retains the sum of the values processed so far, so we do not have to store every previous amount just to add the next one.

A counter similarly retains the number of occurrences processed so far. After each donation, its value changes from 0 to 1, then 2, then 3.

The starting zero is assigned by an initialisation instruction. Declaring a variable introduces its name and type; it does not automatically give it that starting value.

03 | READ THE TWO UPDATE INSTRUCTIONS

Suppose Amount currently holds 7 and Total currently holds 4.

Total ← Total + Amount
Count ← Count + 1

Total ← Total + Amount reads the old total, adds the current amount and stores the new total. Four plus seven becomes eleven.

Count ← Count + 1 reads the old count, adds one and stores the new count. If Count was one, it becomes two. It does not add the amount seven.

The arrow means assignment, not mathematical equality. Evaluate the right-hand expression using the old value, then replace the value associated with the name on the left.

Names are helpful but do not determine behaviour. A variable called Count that adds Amount is accumulating amounts, regardless of its misleading name.

04 | TRACE BOTH VALUES THROUGH THE SAME DATA

Use donations 4, 7 and 2. Both Total and Count start at zero. After each donation, perform both updates.

The same inputs produce two different results
Amount processedTotal after updateCount after update
None yet00
441
7112
2133

The final Total answers “how much?” and the final Count answers “how many?”. Their values need not be equal.

Each row represents the state after that donation has been processed. The values in the next row build on the previous state.

A useful check is to explain the meaning of each current value: after the second donation, Total is the sum of the first two amounts and Count is the number of donations processed.

05 | BUILD A COMPLETE FIXED-NUMBER ALGORITHM

Here is a program design that receives three whole-number donations. Assume each input is a valid non-negative whole number; this example does not add an input-validation routine.

DECLARE Amount : INTEGER
DECLARE Total : INTEGER
DECLARE Count : INTEGER
DECLARE Index : INTEGER
Total ← 0
Count ← 0
FOR Index ← 1 TO 3
    INPUT Amount
    Total ← Total + Amount
    Count ← Count + 1
NEXT Index
OUTPUT "Total donated: ", Total
OUTPUT "Donation entries: ", Count

Total and Count are initialised before the FOR loop. Each repetition inputs one amount and updates both. After all three repetitions, the algorithm outputs the final values.

Index controls the repetition. Count records the number of processed donations. In this fixed-three-input example, Count will always end at three, so it is not strictly necessary if we only need that final number. We include it to make the counting operation visible.

In conditional counting or an unknown-length input sequence, the count may not be known in advance. Those examples show why a separate counter becomes more useful.

06 | COUNT ONLY ITEMS THAT MEET A CONDITION

Suppose a teacher enters five scores and wants to know how many are at least 5. We do not count every input as a qualifying score.

Start QualifyingCount at zero. For each input, test Score >= 5. Only if the condition is true do we add one to QualifyingCount.

DECLARE Score : INTEGER
DECLARE QualifyingCount : INTEGER
DECLARE Index : INTEGER
QualifyingCount ← 0
FOR Index ← 1 TO 5
    INPUT Score
    IF Score >= 5
      THEN
        QualifyingCount ← QualifyingCount + 1
    ENDIF
NEXT Index
OUTPUT QualifyingCount

For scores 4, 5, 8, 2 and 5, the qualifying values are 5, 8 and 5. The final count is three.

Both occurrences of five count because they are separate inputs meeting the condition. Equality is included by >=. A value below five still completes a loop repetition; it simply does not increase this counter.

Do not call this validation. The algorithm classifies the scores for counting; it does not reject a low score or ask for its replacement.

07 | TOTAL AND COUNT THE QUALIFYING VALUES

Now the teacher wants both the sum of scores at least 5 and the number of such scores. Put both updates inside the same condition.

// Initialise both before the input loop
QualifyingTotal ← 0
QualifyingCount ← 0
// Inside each repetition, after INPUT Score
IF Score >= 5
  THEN
    QualifyingTotal ← QualifyingTotal + Score
    QualifyingCount ← QualifyingCount + 1
ENDIF

QualifyingTotal adds Score, while QualifyingCount adds one. With inputs 4, 5, 8, 2 and 5, the total is 18 and the count is 3.

Values after each input has been checked
ScoreScore >= 5?QualifyingTotalQualifyingCount
4False00
5True51
8True132
2False132
5True183

A non-qualifying input changes neither value. If no inputs qualify, both remain zero.

If you later use these values to calculate the average of qualifying scores, divide their total by their count, not by the total number of inputs. Check the count is non-zero before dividing. Averages are developed in the next lesson.

08 | INITIALISE ONCE, IN THE RIGHT PLACE

Total must begin at zero before accumulation. Otherwise the first update does not have an established starting total.

Putting Total ← 0 inside the loop resets it on every repetition. For amounts 4, 7 and 2, the successive totals become 4, 7 and 2 instead of 4, 11 and 13.

The same mistake affects Count: resetting it before every increment leaves it at one after each input.

Initialise before the loop that should accumulate the whole group. If a larger algorithm processes several groups, such as donations for several classes, each class’s total might intentionally reset at the start of that class. Placement depends on what group the total represents.

A good debugging question is: “Should this value describe only the current item, or everything processed in this group so far?”

09 | WHAT IF WE DO NOT KNOW THE NUMBER OF INPUTS?

A collection point might receive an unknown number of donations. One design asks for amounts until a special value signals that entry is finished.

A sentinel is a value reserved to mark the end of input. In this example, −1 is the sentinel because valid donation amounts are non-negative whole numbers.

DECLARE Amount : INTEGER
DECLARE Total : INTEGER
DECLARE Count : INTEGER
Total ← 0
Count ← 0
OUTPUT "Enter a non-negative amount, or -1 to finish"
INPUT Amount
WHILE Amount <> -1 DO
    Total ← Total + Amount
    Count ← Count + 1
    OUTPUT "Enter another amount, or -1 to finish"
    INPUT Amount
ENDWHILE
OUTPUT "Total: ", Total
OUTPUT "Entries: ", Count

The first INPUT occurs before the WHILE condition. If it receives −1 immediately, the loop body runs zero times and both results remain zero.

Inside the body, add the actual amount, increase the count and input the next value. The sentinel ends repetition and is not added or counted as a donation.

This assumes every input is either a valid non-negative amount or −1. A complete system requiring other invalid values to be handled would need additional validation rules.

10 | TRACE THE SENTINEL CAREFULLY

Use inputs 4, 0, 7 and −1. Four is added and counted. Zero is also a valid input: it adds nothing to the amount but still increases the number of recorded donations. Seven is added and counted.

A valid zero is counted; the sentinel is excluded
InputProcessed as an entry?TotalCount
4Yes41
0Yes42
7Yes113
-1No: stops input113

When Amount becomes −1, the next WHILE check is false. The body does not execute for it. The final total is 11 and the count is 3.

Whether zero should count depends on the requirements. Here it represents a valid recorded entry. If the system should count only strictly positive donations, that needs an explicit condition.

Do not choose a sentinel that could also be valid data without a way to distinguish its role. Reserving −1 works here because ordinary amounts cannot be negative.

11 | COUNTERS DO NOT ALWAYS COUNT INPUTS

A counter can track any specified event: accepted bookings, failed login attempts, matching search results or swaps during a sort.

For a booking system, increment AcceptedCount only when a request is accepted. Placing the update before the acceptance decision would also count rejected requests.

For bubble sort, increase SwapCount when two elements are exchanged. ComparisonCount instead increases for every pair comparison, including those that need no swap. The counters answer different questions.

Always explain what event causes the increment. “The counter increases in the loop” is less precise than “The counter increases by one only when the input satisfies the threshold condition.”

If you need two different counts, use two clearly named variables and update each at the appropriate event.

12 | CHOOSE SUITABLE TYPES AND MEANINGFUL NAMES

A count of individual events is normally INTEGER because it represents whole occurrences: zero, one, two and so on.

A total’s type depends on the values added. Whole-number scores can use INTEGER. Quantities with fractional parts need REAL in these introductory pseudocode examples.

For example, three measured lengths 1.5, 2.0 and 0.5 have total 4.0 and count 3. The count remains a whole number even though the total includes fractional values.

Use names that reveal the meaning: TotalLength, ReadingCount or AcceptedBookingCount. An unclear name makes it easier to confuse adding values with counting events.

The arithmetic instructions alone do not explain every real-world rule. Decide whether rejected or zero-valued entries count from the scenario, then place the updates accordingly.

13 | TEST THE MEANING, NOT JUST THE FINAL MESSAGE

Use values whose total differs from their count. Three inputs of one produce total 3 and count 3, so they can hide a mistaken update.

Inputs 4, 7 and 2 are more revealing: total 13 and count 3. For conditional updates, test all qualifying, none qualifying, a mixture and values exactly equal to the threshold.

Threshold is at least five in every row
Five scoresExpected qualifying totalExpected qualifying count
5, 6, 7, 8, 9355
0, 1, 2, 3, 400
4, 5, 8, 2, 5183

For sentinel input, also test −1 as the first entry, a valid zero and a sequence ending with the sentinel. Confirm the sentinel is excluded.

If the displayed number is wrong, trace the values after each update. You may discover a reset inside the loop, an increment outside its condition or input placed so the same value is processed repeatedly.

14 | EXPLAIN THE DIFFERENCE CLEARLY

A clear comparison is: “Totalling adds input values to obtain their sum, whereas counting adds one for each occurrence that meets the specified rule.”

For an explain question, connect placement to effect: “QualifyingCount increases inside the IF branch because only scores at least five should count, therefore a lower score leaves the counter unchanged.”

Do not say “the total increases every time” without checking the data. Adding zero leaves the total unchanged, and a different task allowing negative values could reduce it. The defining operation is adding the value, not guaranteeing growth.

You should now be able to initialise an accumulator, distinguish amount updates from occurrence updates and trace conditional or sentinel-controlled input. The next lesson uses totals and counts to calculate averages alongside maximum and minimum values.

MATCH THE UPDATE TO ITS JOB

Terminology

Terminology

Totalling

Adding values to obtain their sum.

Counting

Recording how many specified items or events occur.

Running total

A variable retaining the sum of values processed so far.

Counter

A variable tracking a number of occurrences.

Accumulator

A variable building up a result across successive operations, such as a running total.

Initialisation

Assigning a starting value before accumulation or counting.

Assignment

Evaluating an expression and storing its result using the name on the left of ←.

Increment

Increasing a value; a simple occurrence counter increases by one.

Conditional count

Counting only events or values meeting a stated condition.

Conditional total

Adding only values meeting a stated condition.

Threshold

A limit used to classify values, such as scores at least five.

Sentinel

A reserved value indicating that input should stop.

INTEGER

A whole-number data type suitable for counts of individual events.

REAL

A numeric data type capable of holding a fractional part.

Loop body

Instructions repeated by a loop.

Trace

A step-by-step record of changing values during execution.

Qualifying value

An input satisfying the condition for inclusion.

Average

A sum divided by the number of values included in that sum.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. For inputs 4, 7 and 2, which are correct?
2. Which update counts one new event?
3. Why initialise before the accumulation loop?
4. Which qualify under Score >= 5?
5. For scores 4, 5, 8, 2, 5, which are correct?
6. Inputs 4, 0, 7, -1 use -1 as a sentinel. Which are correct?
7. Which statements about types are correct?
8. Which tests can reveal mistakes?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Compare totalling and counting.

2. Explain Total ← Total + Amount.

3. Explain the effect of initialising Total inside the input loop before each addition.

4. Describe conditional counting for scores at least five.

5. Explain why the total and count updates belong in the same IF branch when summarising qualifying scores.

6. Explain why the sentinel must not be added or counted.

7. Explain how a valid zero affects total and count in the sentinel example.

8. Suggest why three inputs of one are a weak test for distinguishing total and count updates.

BUILD IT | COUNT AND TOTAL LARGE ORDERS

A canteen receives six whole-number order quantities. Count how many quantities are at least 3 and total only those qualifying quantities. Assume every input is a valid non-negative whole number. Write pseudocode and trace 2, 3, 5, 0, 4 and 1.

Reveal a possible solution
DECLARE Quantity : INTEGER
DECLARE LargeTotal : INTEGER
DECLARE LargeCount : INTEGER
DECLARE Index : INTEGER
LargeTotal ← 0
LargeCount ← 0
FOR Index ← 1 TO 6
    INPUT Quantity
    IF Quantity >= 3
      THEN
        LargeTotal ← LargeTotal + Quantity
        LargeCount ← LargeCount + 1
    ENDIF
NEXT Index
OUTPUT LargeTotal
OUTPUT LargeCount

The qualifying quantities are 3, 5 and 4, giving total 12 and count 3. Zero and the other non-qualifying values complete a repetition but change neither result.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 7.4.3 Totalling and Counting is coming soon. Complete the matching task and written questions in your exercise book.