Programming Basics (Pseudocode Tracing)
The following program was meant to reverse the elements of array a. Array indices start at 1. What does a contain after it runs?
integer array: a ← {1, 2, 3, 4, 5, 6}
integer: n ← 6, t
for (i from 1 to n step 1)
t ← a[i]
a[i] ← a[n − i + 1]
a[n − i + 1] ← t
endfor
- A{6, 5, 4, 3, 2, 1}
- B{6, 5, 4, 4, 5, 6}
- C{1, 2, 3, 4, 5, 6}
Show answer and explanation
Answer: C. {1, 2, 3, 4, 5, 6}
The three lines inside the loop swap a[i] and a[n − i + 1]. For i = 1 to 3 the front and back halves are swapped, giving {6, 5, 4, 3, 2, 1} at that point. But the final value is n, so for i = 4 to 6 the pairs a[4] and a[3], a[5] and a[2], and a[6] and a[1] are swapped again, restoring the original order. To reverse the array, use n ÷ 2 (3 for n = 6) as the final value so that each pair is swapped only once.
- A. This is the result of stopping at i = 3. For i = 4 to 6 the same pairs are swapped again.
- B. This is the result of doing only a[i] ← a[n − i + 1] without t.
- C. Correct. Each pair is swapped twice, so the original order returns.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions