ProgrammingHardTCS Digital · Infosys pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer c = 0
for (i = 1 to 5)
    for (j = i to 5)
        if ((i + j) mod 3 == 0)
            c = c + 1
        end if
    end for
end for
Print c
  1. A. 8
  2. B. 4
  3. C. 9
  4. D. 5

Correct answer: D. 5

Pairs with i ≤ j and i + j divisible by 3: (1,2), (1,5), (2,4), (3,3), (4,5) → 5. Letting j start at 1 counts ordered pairs: 8 (the 4 unequal pairs twice, plus (3,3)); missing (3,3) gives 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic