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.
| Input value | Total after inclusion | EntryCount after inclusion |
|---|---|---|
| 4 | 4 | 1 |
| 7 | 11 | 2 |
| 2 | 13 | 3 |
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: ", EntryCountAssume 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
ENDIFAssume 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| Score | Score >= 5? | QualifyingTotal | QualifyingCount |
|---|---|---|---|
| 4 | FALSE | 0 | 0 |
| 5 | TRUE | 5 | 1 |
| 8 | TRUE | 13 | 2 |
| 2 | FALSE | 13 | 2 |
| 5 | TRUE | 18 | 3 |
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
0QUALIFYING COUNT
0Ready: 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"
ENDIFThis 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"
ENDIFWith 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.