Programming Basics (Pseudocode Tracing)
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?
string array: val ← {"A", "B", "C", "D", "E"}
integer array: next ← {3, 0, 5, 2, 4}
integer: p ← 1
while (p ≠ 0)
output val[p]
p ← next[p]
endwhile
- AA, B, C, D, E
- BC, E, D, B
- CA, C, E, D, B
Show answer and explanation
Answer: C. A, C, E, D, B
With p = 1 the program outputs val[1], A, and p ← next[1] moves p to 3. It then outputs C and moves to next[3] = 5, outputs E and moves to next[5] = 4, outputs D and moves to next[4] = 2, and outputs B and moves to next[2] = 0, which ends the loop. The output is A, C, E, D, B. The order of the list is set by the values in next, not by the order of the array.
- A. This is the order of the array. The traversal order is set by next.
- B. This advances p before output, so the first element A is skipped.
- C. Correct. Indices are visited in the order 1 → 3 → 5 → 4 → 2.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions