ITPEC FE Morning October 2023 Question 7

When the series of stack operations below is performed on an empty stack, which of the following is the data that is read out by the last READ operation? Here, “PUSH x” is the operation to put data x in the stack, “POP” is used to retrieve data from the stack, and “READ” is used to read data from the top of the stack without removing the original data.

PUSH 2 → READ → PUSH 3 → PUSH 6 → POP → READ → PUSH 4

→READ → PUSH 7 → PUSH 5→ POP → POP → READ

Explanation

4 — trace the stack; POP removes the top item, while READ only looks at it.

Stack contents, bottom to top, after each step:

  • •PUSH 2: 2; READ gives 2
  • •PUSH 3, PUSH 6: 2, 3, 6
  • •POP removes 6: 2, 3; READ gives 3
  • •PUSH 4: 2, 3, 4; READ gives 4 and leaves it in place
  • •PUSH 7, PUSH 5: 2, 3, 4, 7, 5
  • •POP removes 5, POP removes 7: 2, 3, 4
  • •READ gives 4

Answer (c)

Why not others:

  • •(a) 2 — the bottom item, returned only by the first READ
  • •(b) 3 — the value of the second READ; it sits under 4 at the end
  • •(d) 6 — removed by the first POP, so it is never read at all

Key rule: A stack is last in, first out: POP removes and READ (peek) returns the most recently pushed item that has not been popped.

Algorithm and Programming · 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.