ProgrammingHardCAT · MBA placement

The procedure below counts the pairs i < j in the array [3, 1, 4, 1, 5] whose sum is even. What is printed?

The procedure below counts the pairs i < j in the array [3, 1, 4, 1, 5] whose sum is even. What is printed?
count = 0
for i = 0 to n - 2
    for j = i + 1 to n - 1
        if (a[i] + a[j]) mod 2 == 0 then count = count + 1
    end for
end for
Print count
  1. A. 4
  2. B. 20
  3. C. 6
  4. D. 12

Correct answer: C. 6

The odd values are 3, 1, 1 and 5, and the even value is 4, so an even pair sum needs two odd values or two even values. There are 6 such pairs among the 10 pairs. Counting odd sums gives 4, the total of pairs is 10, and counting ordered pairs gives 20.

More Pseudocode and Code Tracing questions

Exams that ask this topic