Programming Basics (Pseudocode Tracing)
A queue uses the 4-element string array q as a ring. head and tail start at 1. enq(v) does q[tail] ← v and then tail ← tail mod 4 + 1; deq() returns the value of q[head] and then does head ← head mod 4 + 1. When the following program runs, in which element of q is "E" stored?
enq("A")
enq("B")
enq("C")
deq()
deq()
enq("D")
enq("E")
- Aq[1]
- Bq[3]
- Cq[5]
Show answer and explanation
Answer: A. q[1]
mod is evaluated before +, so tail ← tail mod 4 + 1 cycles tail through 1 → 2 → 3 → 4 → 1. A, B and C go into q[1] to q[3], leaving tail = 4. The two deq() calls remove A and B, making head = 3. D goes into q[4] and tail returns to 4 mod 4 + 1 = 1, so E goes into the freed q[1]. A ring queue (ring buffer) reuses freed slots instead of moving elements forward.
- A. Correct. tail wraps from 4 to 1, and E goes into q[1], freed by an earlier removal.
- B. This assumes the remaining elements move forward on each removal. This method does not move them.
- C. This advances tail from 4 to 5, beyond the array. tail mod 4 + 1 wraps it to 1.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions