ProgrammingHardTCS NQT · Accenture

Array a = [0, 2, 2, 3, 5]. The procedure below counts the positions i (0-based) where a[i] equals i. What is printed?

Array a = [0, 2, 2, 3, 5]. The procedure below counts the positions i (0-based) where a[i] equals i. What is printed?
count = 0
for i = 0 to n - 1
    if a[i] == i then count = count + 1
end for
Print count
  1. A. 3
  2. B. 2
  3. C. 0
  4. D. 5

Correct answer: A. 3

Positions 0, 2 and 3 hold their own index, so the count is 3. Counting the mismatches gives 2, counting positions that hold index minus one gives 0, and the array length is 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic