ITPEC FE Subject B April 2024 Question 8

Topic: Stack

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.

[Program]
global: integer []: content
← {undefined, undefined, undefined, undefined}
global: integer: index ← 1
global: integer: max ← 4 /* max size of the stack */
○ boolean: empty()
if (index = 1)
return true
else
return false
endif
○ boolean: full()
if (A)
return true
else
return false
endif
○ boolean: push(integer: i)
if (not full())
content[index] ← i
index ← B
return true
else
return false
endif
○ integer: pop()
if (not empty())
index ← C
return content[index]
else
return -1
endif

Answer group

OptionABC

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, and push writes to content[index] before changing it, so index is the first free slot and the items sit in content[1] up to content[index - 1].
  • •push stores at the free slot, then moves up: B is index + 1.
  • •The top item is one below the free slot, so pop moves down first and then reads content[index]: C is index - 1.
  • •After four pushes index is 5. Only then is the stack full, and a fifth push would write to content[5], outside the array: A is index > 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 ≥ max reports full at index 4, when only three items are stored, so content[4] is never used
  • •(e), (f), (g) and (h) — A index < max or index ≤ max is already true for the empty stack (index 1), so push refuses every value
  • •(a) — A is right, but B and C are swapped: the first push writes content[1] and sets index to 0, so the next push writes content[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.