Curriculum

Curriculum

Keep a Running Count Across a List

Scenario

Count how many study rooms have at least 1 free seat in freeSeatList = [0, 2, 1, 0].

  1. 1Start: openRooms = 0 -> room 0 has 0 seats
  2. 2Room 1 has 2 seats (2 > 0 is true)
  3. 3Room 2 has 1 seat (1 > 0 is true)
  4. 4Room 3 has 0 seats -> loop ends

Try it yourself

Step through each room and track openRooms from 0 to its final value.

Reveal the explanation
  1. Start: openRooms = 0 -> room 0 has 0 seats

    0 > 0 is false. openRooms remains 0.

  2. Room 1 has 2 seats (2 > 0 is true)

    Increment counter: openRooms becomes 1.

  3. Room 2 has 1 seat (1 > 0 is true)

    Increment counter: openRooms becomes 2.

  4. Room 3 has 0 seats -> loop ends

    0 > 0 is false. Final returned openRooms = 2.

Two common mistakes break counters: resetting count = 0 inside the loop body, or adding the room’s seat count when you meant to count matching rooms (+1).

Review first
Download shared test cases

Your turn

Trace both countOpenRooms([0, 2, 1]) and totalFreeSeats([0, 2, 1]) and contrast the two final numbers.

Common mistake Adding seats (+ item) when the rule asks for the number of open rooms (+ 1).

Check your work

countOpenRooms -> 2 rooms; totalFreeSeats -> 3 seats.

Quick check

What happens if you put "count = 0" inside the loop body instead of before the loop?
Show the answer and reasoning

Correct answer count resets on every item and only reflects the very last item

Resetting inside the loop wipes out all earlier increments.