ITPEC FE Subject B October 2025 Question 8
From the answer group below, select the correct combination of answers to be inserted into A and B in the program. Here, the array index starts at 1.
Stack stores data using first-in, last-out ordering. Here, the items stored in the stack are integer values, and the stack is controlled by the procedure push and the function pop. The procedure push adds an item given as an argument to the top of the stack, and the function pop removes the top item from the stack and returns it. The global variable stck is an array of 10 integers that stores the stack items, and the global variable tos is the pointer that points to the topmost item of the stack.
Answer group
Explanation
A: tos ← tos + 1, B: item ← stck[tos] then tos ← tos - 1 — tos is the index of the top item, and 0 means the stack is empty.
- •The empty test in
popistos < 1and the full test inpushistos = 10, so the items occupystck[1]tostck[tos]. - •
push: the slot attosis occupied, so the pointer first moves up to the free slot, thenstck[tos] ← itemstores there: A istos ← tos + 1. - •
pop: the top item is atstck[tos]itself, so it is read first and then the pointer moves down: B isitem ← stck[tos],tos ← tos - 1.
Trace: push 5 and push 8 leave tos at 2 with 5 and 8 in stck[1] and stck[2]; pop then reads stck[2], returns 8, and leaves tos at 1.
Answer (b)
Why not others:
- •(e), (f), (g) and (h) — A
tos ← tos - 1moves the pointer down on a push; the first push stores intostck[-1], outside the array - •(a) — B moves
tosup after reading, so the stack never shrinks and the next pop reads an empty slot - •(c) — B moves
tosup before reading, so it returns the empty slot above the top - •(d) — B moves
tosdown before reading, so it returns the item below the top, andstck[0]when one item is left
Key rule: Fix what the pointer means first: if it indexes the top item, push increments then writes and pop reads then decrements; if it indexes the next free slot, the order is reversed.
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.