ITPEC FE Subject B April 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.
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.
Answer group
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
spafter reading returns the top once, then movesspto n + 1, an undefined slot, and away from the stop value, eventually paststack[100]. - •(c) and (g) — raising
spbefore reading makes the very first pop readstack[, undefined, and append it.n + 1] - •(b) — the right pop, but with A = -1 the loop pops again at
sp= 0 and readsstack[0], outside the array. - •(d) and (h) — lowering
spbefore reading skips the top: the first pop returnsstack[, the last character is lost, and the pop atn - 1] sp= 1 readsstack[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.