Programming Basics (Pseudocode Tracing)

Array indices start at 1. The following program looks for the largest element. What is the value of m after it runs?

integer array: a ← {3, 8, 2, 8, 5}
integer: m ← 1
for (i from 2 to 5 step 1)
  if (a[i] > a[m])
    m ← i
  endif
endfor
  1. A2
  2. B4
  3. C8
Show answer and explanation

Answer: A. 2

m is the index of the largest element seen so far. At i = 2, a[2] = 8 > a[1] = 3, so m = 2. At i = 4, a[4] = 8 equals a[2] = 8, so > does not hold and m does not change. When the maximum appears more than once, the index of its first occurrence, 2, remains. With ≧ the result would be the index of the last occurrence, 4.

  • A. Correct. m is not updated for equal values, so the index of the first maximum, 2, remains.
  • B. This is the result with the condition a[i] ≧ a[m].
  • C. This is the maximum value itself. m is assigned an index.
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 was meant to reverse the elements of array a. Array indices start at 1. What does a contain after it runs?
  2. Array indices start at 1. What does array a contain after the following program runs?
  3. Array indices start at 1. The following program compares adjacent elements. What is the value of c after it runs?
  4. 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?
  5. 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?