ITPEC FE Subject B April 2024 Question 8
ITPEC FE Subject B April 2024 — Question 8 of 20
Implementing a stack with an array where index tracks the next free slot.
The stack uses a fixed-size array content[1..4] with index starting at 1 (empty stack) and max = 4.
How `index` works:
- index always points to the next free slot (where the next push will write)
- Empty: index = 1 (nothing stored yet)
- Full: index = 5 (all 4 slots used, no room left)
Blank A — `full()`:
The stack is full when all slots are used, i.e. index has moved past max. That means index > max (when index = 5, since 5 > 4). Using index ≥ max would incorrectly block the 4th push (when index = 4, only 3 elements stored).
Blank B — `push()`:
After writing content[index] ← i, move index forward: index ← index + 1.
Blank C — `pop()`:index points to an empty slot. The top element is at index - 1. First decrement: index ← index - 1, then return content[index].
Trace example (push 10, 20, 30, 40 then pop):
| Action | Before | Write to | After index |
|---|---|---|---|
| push(10) | index=1 | content[1]=10 | index=2 |
| push(20) | index=2 | content[2]=20 | index=3 |
| push(30) | index=3 | content[3]=30 | index=4 |
| push(40) | index=4 | content[4]=40 | index=5 |
| full()? | index=5 | 5 > 4 = true | — |
| pop() | index=5 | index←4, return content[4]=40 | index=4 |
Why not others:
- (a) index > max + index - 1 + index + 1 — B and C are swapped: push would decrement (shrink) and pop would increment (grow)
- (c) index ≥ max — blocks 4th push (index=4, 4≥4=true with only 3 elements stored)
- (d) index ≥ max + index + 1 + index - 1 — same ≥ problem as (c), wastes one slot
- (e)-(h) index < max or index ≤ max — these are wrong comparisons for "full" (they check the opposite condition)
Key rule: when index tracks the next free slot, the stack is full when index > max (strictly greater), push increments index, and pop decrements before returning.
AI-generated — may contain errors
The original exam layout is preserved in the image so diagrams, formulas, tables, and code remain accurate.
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.