ProgrammingHardTCS NQT · Accenture

The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?

The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?
count = 0
for i = 0 to n - 2
    for j = i + 1 to n - 1
        if a[i] + a[j] == 8 then count = count + 1
    end for
end for
Print count
  1. A. 4
  2. B. 17
  3. C. 9
  4. D. 8

Correct answer: A. 4

The matching pairs are (1,7), (5,3) twice, and (6,2), so the answer is 4. Counting with a <= test adds more pairs, the ordered count including i = j gives 9, and counting ordered pairs with i not equal to j gives 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic