ProgrammingHardTCS NQT · Accenture

A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?

A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?
count = 0
for i = 1 to 6
    for j = 1 to i
        if (i + j) mod 2 == 0 then count = count + 1
    end for
end for
Print count
  1. A. 6
  2. B. 12
  3. C. 18
  4. D. 9

Correct answer: B. 12

Listing the pairs with j at most i and i + j even gives 12 pairs. Requiring j < i gives 6, using all j up to 6 gives 18, and counting odd sums gives 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic