CIE IGCSE | 8.1.4D Totalling and Counting in Programs

Lesson objective

Initialise and update running totals and counts, apply conditions to qualifying inputs, and calculate a mean using the matching count with a zero guard.

Learn

8.1.4D | TOTALLING AND COUNTING IN PROGRAMS

01 | TWO DIFFERENT QUESTIONS ABOUT THE SAME DATA

Three students borrow four, seven and two books. How many books were borrowed altogether? How many students supplied a borrowing record?

The first answer is thirteen books. The second is three students. You used the same inputs to answer two different questions.

Totalling adds the values. Counting records how many items or events are included, usually adding one for each.

A program must keep those jobs separate. Total ← Total + Value answers “how much altogether?” Count ← Count + 1 answers “how many items?” Neither update automatically performs the other job.

02 | START A RUNNING TOTAL AT ZERO

A running total is a sum updated as each value is processed. Before any value has been added, its starting value is zero.

DECLARE Total : INTEGER
DECLARE Value : INTEGER
Total ← 0
Value ← 4
Total ← Total + Value
Value ← 7
Total ← Total + Value
Value ← 2
Total ← Total + Value

The first update reads zero plus four and stores four. The next reads four plus seven and stores eleven. The final update reads eleven plus two and stores thirteen.

Initialisation means giving the variable its starting value. A declaration alone does not specify that zero. You must provide it before an update reads the existing Total.

The old total is deliberately part of the expression. Total ← Value would replace the summary with the current value, not accumulate earlier values.

03 | START A COUNT AT ZERO AND ADD ONE

A count begins at zero because no items have yet been included. Each item adds one, regardless of its numerical value.

DECLARE EntryCount : INTEGER
EntryCount ← 0
EntryCount ← EntryCount + 1
EntryCount ← EntryCount + 1
EntryCount ← EntryCount + 1

After the three updates, EntryCount is three. The amounts four, seven and two do not appear in this count expression.

Both summaries are initialised to zero before the first input
Input valueTotal after inclusionEntryCount after inclusion
441
7112
2133

EntryCount ← EntryCount + Value would total the input values rather than count their records. Choose names that expose the distinction, such as TotalBooks and StudentCount.

04 | A LOOP REPEATS THE TWO UPDATES

A loop body is the instruction or group of instructions inside the loop that repeats. Here, the body prompts, receives a value and updates both summaries.

DECLARE ItemIndex : INTEGER
DECLARE Value : INTEGER
DECLARE Total : INTEGER
DECLARE EntryCount : INTEGER
Total ← 0
EntryCount ← 0
FOR ItemIndex ← 1 TO 3
    OUTPUT "Enter value ", ItemIndex
    INPUT Value
    Total ← Total + Value
    EntryCount ← EntryCount + 1
NEXT ItemIndex
OUTPUT "Total: ", Total
OUTPUT "Entries: ", EntryCount

Assume valid whole-number input. With four, seven and two, the final results are thirteen and three. Final outputs occur after the body has repeated for all inputs.

The initialisations happen once before FOR. If you reset Total or EntryCount inside the body, earlier contributions disappear on each iteration.

The known three-entry count makes EntryCount redundant in this particular example, but it shows the counting pattern that becomes useful for conditional or unknown-length processing.

05 | THE LOOP COUNTER IS NOT EVERY SUMMARY COUNT

ItemIndex identifies the current iteration. EntryCount records included items. They happen to follow the same numbers in an unconditional three-input example, but their roles are different.

Suppose five scores are supplied and only scores at least five should count towards a summary. The loop still receives five inputs, but the qualifying count may be three, one or zero.

A qualifying value is a value meeting the stated rule for inclusion. For the rule Score >= 5, four does not qualify and five does.

Do not use the loop counter as a substitute for the number of qualifying values. Nor should you rely on a particular FOR-counter value after NEXT to obtain a summary.

06 | COUNT ONLY WHEN THE CONDITION HOLDS

A conditional count adds one only when the current value meets the inclusion rule.

IF Score >= 5
  THEN
    QualifyingCount ← QualifyingCount + 1
ENDIF

Assume the variables are declared appropriately and QualifyingCount has been initialised to zero before repetition. For scores four, five, eight, two and five, only five, eight and five cause a count update.

The final QualifyingCount is three. Rejected-by-this-summary does not mean invalid input: four and two can be valid scores that simply do not meet the summary’s threshold.

Use the comparison that matches the requirement. “At least five” includes five, while “greater than five” would exclude it and give a different count.

07 | KEEP THE CONDITIONAL TOTAL AND COUNT TOGETHER

If both summaries should describe the same qualifying inputs, place both updates inside the same selection.

IF Score >= 5
  THEN
    QualifyingTotal ← QualifyingTotal + Score
    QualifyingCount ← QualifyingCount + 1
ENDIF
The total and count both start at zero
ScoreScore >= 5?QualifyingTotalQualifyingCount
4FALSE00
5TRUE51
8TRUE132
2FALSE132
5TRUE183

The summary contains eighteen points across three qualifying scores. If the total included every input but the count included only qualifying ones, dividing them would mix two different data sets.

Separate names such as AllTotal and QualifyingTotal can help when a task needs both summaries. Update each according to its own clearly stated rule.

08 | FOLLOW THE CONDITIONAL SUMMARY INTERACTIVELY

Predict the new total and count before each step. The inclusion rule is Score >= 5. Try the mixed, all-qualifying and none-qualifying data sets.

:

QUALIFYING TOTAL

0

QUALIFYING COUNT

0

Ready: both summaries are zero.

    The final mean is calculated only after every score has been examined, and only if at least one qualifies.

    09 | A MEAN NEEDS THE MATCHING COUNT

    The arithmetic mean is the sum of a set of values divided by the number of values in that set. Both parts must refer to the same inputs.

    For five, eight and five, the total is eighteen and the count is three. Their mean is six. Dividing eighteen by all five supplied scores gives three point six, which is not the mean of the qualifying scores.

    Average ← QualifyingTotal / QualifyingCount

    This fragment assumes a positive QualifyingCount; we add the guard next. Declare Average as REAL because a mean can have a fractional part even when all scores are integers.

    For values one and two, a total of three divided by a count of two gives one point five. Whole-number inputs do not imply a whole-number result.

    10 | CHECK ZERO BEFORE DIVIDING

    If no score qualifies, both qualifying summaries stay zero. Division by zero is undefined, so do not calculate the mean before testing the count.

    IF QualifyingCount > 0
      THEN
        Average ← QualifyingTotal / QualifyingCount
        OUTPUT "Mean qualifying score: ", Average
      ELSE
        OUTPUT "No qualifying scores"
    ENDIF

    This is a zero guard: a condition preventing a division with a zero denominator. The denominator is the number by which you divide.

    A valid mean of zero is different from no mean. Values minus one and one have total zero and count two, giving mean zero. With no included values, count zero means the mean is not calculated.

    Do not output Average on the no-qualifying path unless the algorithm has assigned an appropriate meaning to it. The alternative message makes the absence of data clear.

    11 | READ THE COMPLETE CONDITIONAL PROGRAM

    This receives five valid whole-number scores from zero to ten. It outputs the total and count of scores at least five, then their mean or an alternative. Input validity is assumed; the inclusion threshold is not a validation retry.

    DECLARE StudentIndex : INTEGER
    DECLARE Score : INTEGER
    DECLARE QualifyingTotal : INTEGER
    DECLARE QualifyingCount : INTEGER
    DECLARE Average : REAL
    QualifyingTotal ← 0
    QualifyingCount ← 0
    FOR StudentIndex ← 1 TO 5
        OUTPUT "Enter score for student ", StudentIndex
        INPUT Score
        IF Score >= 5
          THEN
            QualifyingTotal ← QualifyingTotal + Score
            QualifyingCount ← QualifyingCount + 1
        ENDIF
    NEXT StudentIndex
    OUTPUT "Total qualifying score: ", QualifyingTotal
    OUTPUT "Qualifying scores: ", QualifyingCount
    IF QualifyingCount > 0
      THEN
        Average ← QualifyingTotal / QualifyingCount
        OUTPUT "Mean qualifying score: ", Average
      ELSE
        OUTPUT "No qualifying scores"
    ENDIF

    With four, five, eight, two and five, results are total eighteen, count three and mean six. With four, two, zero, one and three, results are total zero, count zero and No qualifying scores.

    Both paths still output their total and count. Only the mean calculation is conditional on a non-zero count.

    12 | ZERO AND NEGATIVE VALUES NEED THEIR STATED RULE

    Zero can be an included value. If all three values three, zero and two are included, the sum is five and the item count is three. Adding zero leaves the sum unchanged but still adds one to the count.

    Negative values can also be included when the task permits them. For temperatures minus one and minus three point five, the total is minus four point five and the count is two.

    The count is not inferred from whether the total changes. Nor should a program treat every non-positive value as invalid without a requirement saying so.

    For a sentinel task, the stop marker is different from an ordinary amount. Exclude it from both addition and counting, even if it is represented by a negative number.

    13 | PLACE UPDATES AFTER ACCEPTANCE

    A class attendance input may need retries until it is in range. If the task summarises accepted classes, update the total and count only after that retry has succeeded.

    Adding on every attempt can include invalid values; counting on every attempt can count one class several times. The loop structure and update placement determine which event counts as an item.

    In a REPEAT sentinel loop, the sentinel is received inside the body. Guard both updates with a non-sentinel condition. In a primed WHILE sentinel loop, the before-body condition can exclude the stop marker.

    Ask “what exactly am I counting?” before choosing the update location: input attempts, accepted records and qualifying values are different possible counts.

    14 | TEST THE TWO SUMMARIES SEPARATELY

    Use mixed qualifying and non-qualifying values to check the inclusion condition. Test the exact threshold to expose a mistaken > instead of >=.

    Use no qualifying values to check the zero guard. Use exactly one qualifying value: its mean should equal that value. Use a data set giving a fractional mean to check the result type.

    For unconditional summaries, include a valid zero and, where permitted, negative values. Check that the count increases for each included item even if its addition changes nothing.

    When a result is wrong, check the initialisation, included values, update expression and denominator independently. A correct count does not prove a correct total, and a correct total does not prove the average uses the right count.

    15 | COMMON MISTAKES AND CLEAR EXPLANATIONS

    Count adds Value: use plus one when counting items.

    Total replaced by Value: use the old total plus the current value when accumulating.

    Summaries reset inside the loop: initialise once before the relevant repetition.

    Count uses every input but total uses a subset: match the data set when calculating a mean.

    Division before the guard: check the count first, then calculate.

    A useful explanation is: “Both updates run only for scores at least five, so the total and count describe the same qualifying values. The count is checked before division because no qualifying scores would give a zero denominator.”

    The next lesson introduces string length and substrings. Keep the distinction between an item’s value and the number of items: you will use counting ideas in text processing too.

    MATCH THE SUMMARY STEP TO ITS PURPOSE

    Terminology

    Terminology

    Totalling

    Adding included values to obtain a sum.

    Counting

    Recording how many included items or events there are.

    Running total

    A sum updated as values are processed.

    Initialisation

    Giving a summary its starting value before updates.

    Accumulation

    Adding to a previous summary rather than replacing it with the latest value.

    Counting update

    Adding one for each included item.

    Qualifying value

    A value meeting the stated rule for inclusion.

    Conditional count

    A count updated only when an inclusion condition is true.

    Conditional total

    A sum updated only when an inclusion condition is true.

    Loop body

    The instruction or group of instructions repeated inside a loop.

    Loop counter

    A variable controlling or identifying iterations rather than necessarily counting qualifying items.

    Arithmetic mean

    The total of included values divided by their count.

    Denominator

    The number by which another number is divided.

    Zero guard

    A condition preventing division when the count is zero.

    REAL

    A numeric type suitable for results that may contain a fractional part.

    Sentinel

    A special stop marker excluded from ordinary-item processing.

    Accepted record

    A record that has passed the required checks before summary updates.

    Inclusion threshold

    A boundary determining which values contribute to a summary.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

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

    1. For values four, seven and two, which are correct?
    2. Which instruction counts one included item?
    3. Where should a running total be initialised for a complete input loop?
    4. Scores are four, five, eight, two and five. Include scores at least five. Which are correct?
    5. Which denominator gives the qualifying mean for those scores?
    6. What should happen when no score qualifies?
    7. A valid zero value is included in an unconditional summary. Which are correct?
    8. Which data set exposes a fractional-mean requirement?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Compare totalling and counting using four, seven and two.

    2. Explain why Total ← Total + Value needs a starting Total.

    3. Calculate the total, count and mean of scores at least five in four, five, eight, two and five.

    4. Explain why dividing that qualifying total by five is wrong.

    5. Explain why Count ← Count + Value does not count items.

    6. Explain why a zero guard belongs before the mean calculation.

    7. State what happens to a total and count when an included value is zero.

    8. Suggest tests for a conditional summary and explain their purposes.

    BUILD IT | BELOW-ZERO TEMPERATURES

    Receive four valid temperatures, which may have fractional parts. Count temperatures strictly below zero, total only those temperatures and output their mean. If none is below zero, output No below-zero readings instead of a mean. Output the below-zero total and count in either case. Write declarations, prompts and the complete algorithm. Trace 2.5, -1.0, 0.0 and -3.5.

    Reveal one possible solution
    DECLARE ReadingIndex : INTEGER
    DECLARE Temperature : REAL
    DECLARE NegativeTotal : REAL
    DECLARE NegativeCount : INTEGER
    DECLARE Average : REAL
    NegativeTotal ← 0.0
    NegativeCount ← 0
    FOR ReadingIndex ← 1 TO 4
        OUTPUT "Enter temperature for reading ", ReadingIndex
        INPUT Temperature
        IF Temperature < 0.0
          THEN
            NegativeTotal ← NegativeTotal + Temperature
            NegativeCount ← NegativeCount + 1
        ENDIF
    NEXT ReadingIndex
    OUTPUT "Below-zero total: ", NegativeTotal
    OUTPUT "Below-zero readings: ", NegativeCount
    IF NegativeCount > 0
      THEN
        Average ← NegativeTotal / NegativeCount
        OUTPUT "Mean below-zero temperature: ", Average
      ELSE
        OUTPUT "No below-zero readings"
    ENDIF

    The included readings are minus one and minus three point five: total minus four point five, count two and mean minus two point two five. Zero is valid input but does not satisfy the strictly-below-zero condition.

    Test: four non-negative readings should produce total zero, count zero and the alternative message. A single negative reading should produce a mean equal to that reading.

    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 8.1.4D Totalling and Counting in Programs is coming soon. Complete the matching task and written questions in your exercise book.