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
  1. A{6, 5, 4, 3, 2, 1}
  2. B{6, 5, 4, 4, 5, 6}
  3. 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.
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. Array indices start at 1. What does array a contain after the following program runs?
  2. Array indices start at 1. The following program compares adjacent elements. What is the value of c after it runs?
  3. m[i, j] is the element in row i, column j of the 2D array m, and indices start at 1. What is the value of s after the following program runs?
  4. The following program copies the elements of the 2D array m with 4 rows and 5 columns into the 20-element array b. m[i, j] is the element in row i, column j, and indices start at 1. At which index of b is m[3, 2] stored?
  5. Array indices start at 1, and + concatenates strings. What is the value of r after the following program runs?