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.
| Amount processed | Total after update | Count after update |
|---|---|---|
| None yet | 0 | 0 |
| 4 | 4 | 1 |
| 7 | 11 | 2 |
| 2 | 13 | 3 |
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: ", CountTotal 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 QualifyingCountFor 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
ENDIFQualifyingTotal adds Score, while QualifyingCount adds one. With inputs 4, 5, 8, 2 and 5, the total is 18 and the count is 3.
| 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 |
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: ", CountThe 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.
| Input | Processed as an entry? | Total | Count |
|---|---|---|---|
| 4 | Yes | 4 | 1 |
| 0 | Yes | 4 | 2 |
| 7 | Yes | 11 | 3 |
| -1 | No: stops input | 11 | 3 |
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.
| Five scores | Expected qualifying total | Expected qualifying count |
|---|---|---|
| 5, 6, 7, 8, 9 | 35 | 5 |
| 0, 1, 2, 3, 4 | 0 | 0 |
| 4, 5, 8, 2, 5 | 18 | 3 |
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.