SECTION 03 / 15

Below average: finish one pass before filtering

2 min read
On this page 3 headings

We want the students whose Mathematics mark is below the average of the whole class. A running average changes whenever another card is read. Deciding permanently from that unfinished average can give the wrong answer.

First compute the final average. Then compare every Mathematics mark with that fixed value.
First compute the final average. Then compare every Mathematics mark with that fixed value.
REAL COURSE DATA · FOLLOW THE PROCEDURE

Find Mathematics marks below the final average

Read the current record, check the explanation, and watch the variables. Use Back to revisit any step.

Ready

CURRENT RECORD

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Start at the first step. Watch the current row and the values we remember.

Pass 1 computes; pass 2 selects

Sum = 0
Count = 0
for each row X in Scores {
    Sum = Sum + X.Mathematics
    Count = Count + 1
}
if (Count == 0) { report "No average"; stop }
Average = Sum / Count
for each row X in Scores {
    if (X.Mathematics < Average) { record X.CardNo }
}

Our 30 cards sum to 2,171, so the exact average is 2171/30 ≈ 72.3667. For integer marks, 72 is below this average and 73 is above it. Compare with the unrounded average, even when the display is rounded.

MeaningResult
Below-average IDs0, 1, 2, 3, 5, 9, 10, 12, 13, 17, 18, 19, 22, 24, 29
Number below average15
Visits for two full passes30 + 30 = 60

Two passes are not nested loops

The first loop ends before the second begins. We do not scan all 30 cards again inside each visit. Both passes may read the data without changing it; with physical piles, restore the cards before pass 2.

Below average does not always mean half

For the tiny example 50, 50, 50, 100, the average is 62.5 and three of four values are below it. If all values are equal, none is strictly below average. The result 15 out of 30 is a property of our supplied marks, not a general law.

Try it yourself

Why can a running average misclassify an earlier card?

Show explained answer

A later value can move the average up or down. An earlier value may cross the new threshold.

Try it yourself

Does a Mathematics mark of 72 pass the below-average test here?

Show explained answer

Yes. 72 < 2171/30.

Try it yourself

Are the two loops one inside the other?

Show explained answer

No. They run sequentially: finish pass 1, then start pass 2.

Try it yourself

What if Count is zero?

Show explained answer

Do not divide by zero. Report that there is no average.

Try it yourself

How many of 50,50,50,100 lie below their mean?

Show explained answer

Three. Their mean is 62.5.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑