AP Computer Science Principles algorithm questions often use short pseudocode, but the reasoning can be surprisingly dense. Students need to track list indexes, procedure parameters, counters, and return values at the same time.
Scenario: anonymous club survey
A school club collects anonymous weekly attendance counts. The list below stores how many students attended each meeting:
attendance ← [18, 22, 15, 22, 27, 19, 22]
The club wants to count how many meetings had at least a target attendance value.
PROCEDURE countAtLeast(values, target)
{
count ← 0
i ← 1
REPEAT LENGTH(values) TIMES
{
IF values[i] ≥ target
{
count ← count + 1
}
i ← i + 1
}
RETURN count
}
Trace the procedure call
For countAtLeast(attendance, 22), the procedure visits every list element. The values meeting the condition are 22, 22, 27, and 22, so the return value is 4.
| i | values[i] | Condition | count |
|---|---|---|---|
| 1 | 18 | false | 0 |
| 2 | 22 | true | 1 |
| 3 | 15 | false | 1 |
| 4 | 22 | true | 2 |
| 5 | 27 | true | 3 |
| 6 | 19 | false | 3 |
| 7 | 22 | true | 4 |
Common AP CSP traps
- Forgetting that AP CSP lists are commonly shown as 1-indexed in pseudocode.
- Confusing
REPEAT LENGTH(values) TIMESwith a loop that stops before the final item. - Thinking the procedure changes the original list when it only reads it.
- Returning
values[i]instead of returning the accumulated count.
Practice extension
Modify the procedure so it returns the percentage of meetings at or above the target. Then test it with a target that no meeting reaches and a target that every meeting reaches.
