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")
  1. Aq[1]
  2. Bq[3]
  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.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. The following program outputs a linked list, whose elements are linked by the array next, by following it from the element at index 1. Array indices start at 1. A next value of 0 marks the end of the list. What sequence of values is output?
  2. The following program inserts "F", in val[6], right after "C" (index 3) in the linked list A → C → E → D → B, linked by the array next, and then outputs the list from the element at index 1. Array indices start at 1. A next value of 0 marks the end of the list. What should replace 【a】 so that the output is A, C, F, E, D, B?
  3. The following for loop increases its control variable by 5. What is the value of c after it runs?
  4. In the following program, and does not evaluate its right side when the left side is false (short-circuit evaluation). cnt is a global variable. What is the value of cnt after the program runs?
  5. The following program searches the n-element array a for the value x and stores the index where it is found in i. Array indices start at 1. and and or do not evaluate their right side when the left side alone decides the result. Which condition in 【a】 reads a[n + 1], outside the array, when x is not in a?