ITPEC FE Subject B April 2024 Question 8
From the answer group below, select the correct combination of answers to be inserted into A through C in the program. Here, the array index starts at 1.
The program implements a stack. The stack implementation only accepts positive integers. The function empty checks whether the stack is empty. The function full checks whether the stack is full. If the stack is not full, the function push pushes an element with a specified value onto the stack. If the stack is not empty, the function pop removes an element from the stack and returns its value. In the program, areas outside of the array must not be referenced.
Answer group
Explanation
A: index > max, B: index + 1, C: index - 1 — index is the next free slot: 1 means empty, and max + 1 means all four slots are filled.
- •
empty(tests) index = 1, andpushwrites tocontent[index]before changing it, soindexis the first free slot and the items sit incontent[1]up tocontent[.index - 1] - •
pushstores at the free slot, then moves up: B isindex + 1. - •The top item is one below the free slot, so
popmoves down first and then readscontent[index]: C isindex - 1. - •After four pushes
indexis 5. Only then is the stack full, and a fifth push would write tocontent[5], outside the array: A isindex > max.
Trace: push 10, 20, 30 and 40 take index to 2, 3, 4 and 5; full( then tests 5 > 4, true; pop sets index to 4 and returns 40.
Answer (b)
Why not others:
- •(c) and (d) — A
index ≥ maxreports full atindex4, when only three items are stored, socontent[4]is never used - •(e), (f), (g) and (h) — A
index < maxorindex ≤ maxis already true for the empty stack (index1), sopushrefuses every value - •(a) — A is right, but B and C are swapped: the first push writes
content[1]and setsindexto 0, so the next push writescontent[0], outside the array
Key rule: Work out what the index means from the code you are given; a next-free-slot index is incremented after writing, decremented before reading, and reaches max + 1 when the stack is full.
Stack · AI-written, may contain errors
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.