Skip to main content

Pilot · Lab P04 · 45 minutes

A reusable counting procedure

Two pages copy the same counting loop with different fixed numbers. Refactor them into one procedure, countAvailable(capacities, minimum), that RETURNs a count. Then show that two calls with different arguments give different results.

Predict first

Write your predictions before you use the tool.

  1. For capacities [0, 5, 2, 8], predict countAvailable(capacities, 3) and countAvailable(capacities, 2).
  2. What should countAvailable([], 3) return, and why is that not an error?

Practice tool

The call explorer evaluates the fixed countAvailable procedure for two calls you set up side by side and shows what each call returns. Unlike the P03 filter, it returns a single number, not a list. It does not run your code.

Call explorer · countAvailable(capacities, minimum)

Up to 12 whole numbers, comma separated. Leave empty for [].

countAvailable(capacities, 3) returns 2

0· 5✓ 2· 8✓

countAvailable(capacities, 2) returns 3

0· 5✓ 2✓ 8✓

✓ counted · not counted. Each call returns one number.

Starter

Starter (duplicated): two copied loops · AP CSP pseudocode
bigRooms ← 0FOR EACH seats IN capacities{  IF (seats ≥ 3) { bigRooms ← bigRooms + 1 }}smallRooms ← 0FOR EACH seats IN capacities{  IF (seats ≥ 2) { smallRooms ← smallRooms + 1 }}
Target signature · AP CSP pseudocode
PROCEDURE countAvailable(capacities, minimum){  // your loop here  RETURN(count)}

Worked case

Worked call: countAvailable([0, 5, 2, 8], 3)
seatsseats ≥ 3?count
0no0
5yes1
2no1
8yes2

RETURN(2) hands the value back to the caller, so x ← countAvailable(capacities, 3) stores 2. DISPLAY would only show it and give the caller nothing to store.

Build

  1. Write countAvailable using the parameter minimum everywhere the copies used 3 or 2.
  2. Replace both copied loops with two calls.
  3. Use the call explorer to check all four tests and to compare two calls side by side.

Tests

Tests for this lab
InputExpectedWhy this test
countAvailable([0, 5, 2, 8], 3)2Normal case.
countAvailable([0, 5, 2, 8], 2)3Different argument, different result: 2 now counts.
countAvailable([3, 3], 3)2Duplicates are counted.
countAvailable([], 3)0The count starts at 0 and no pass happens.

Explain and reflect

Explain

  1. Explain how the minimum parameter changes what the same procedure returns, using your two calls as evidence.
  2. Explain why RETURN, not DISPLAY, lets the caller use the result.

Reflect

  1. If a bug is found in the comparison, how many places must you fix now compared with before?
  2. What would a third page need to do to reuse your procedure?

What this lab does not do

  • The explorer evaluates only the fixed countAvailable; it does not run your procedure.
  • Lists are limited to 12 whole numbers from 0 to 999.
  • Nothing in the explorer is saved.