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
- A2
- B4
- 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.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions