ITPEC FE Subject B April 2025 Question 8

Topic: Stack

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.

The function reverse takes a string inputStr as a parameter and returns the reversed string. Here, the length of the string given to inputStr is 100 or less. In the program, areas outside of the arrays must not be referenced and the undefined value must not be appended to a string.

[Program]
global: character []: stack ← {100 undefined}
global: integer: sp ← 0
○ string: reverse(string: inputStr)
integer: n ← length of inputStr
integer: i
character: x, v
string: outputStr ← ""
for (increase i from 1 to n by 1)
x ← the i-th character of string inputStr
push(x)
endfor
while (sp ≠ A)
v ← pop()
append v to outputStr
endwhile
return outputStr
○ push(character: x)
sp ← sp + 1
stack[sp] ← x
○ character: pop()
character: retvar
B
return retvar

Answer group

OptionAB

Explanation

A: 0, B: retvar ← stack[sp], then sp ← sp - 1 — push raises sp before writing, so sp points at the top element and 0 means empty.

push does sp ← sp + 1, then stack[sp] ← x. After n pushes the characters sit in stack[1] to stack[n] and sp = n, the index of the top element itself. pop must mirror this in reverse: read stack[sp] first, then lower sp. After n pops sp is back at its initial value 0, so the loop must stop there: A = 0.

Trace with "abc": the pushes leave a, b, c in stack[1..3] with sp = 3. The pops return c (sp 2), b (sp 1), a (sp 0), the loop stops, and the function returns "cba".

Answer (f)

Why not others:

  • •(a) and (e) — raising sp after reading returns the top once, then moves sp to n + 1, an undefined slot, and away from the stop value, eventually past stack[100].
  • •(c) and (g) — raising sp before reading makes the very first pop read stack[n + 1], undefined, and append it.
  • •(b) — the right pop, but with A = -1 the loop pops again at sp = 0 and reads stack[0], outside the array.
  • •(d) and (h) — lowering sp before reading skips the top: the first pop returns stack[n - 1], the last character is lost, and the pop at sp = 1 reads stack[0].

Key rule: Pop mirrors push in reverse order (increment then write means read then decrement), and the stack is empty when the pointer is back at its initial value.

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.