ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer s = 0
for (each i from 1 to 4)
    for (each j from 1 to 4)
        if ((i * j) mod 3 == 0)
            s = s + i
        else
            s = s - j
        end if
    end for
end for
Print s
  1. A. -21
  2. B. 2
  3. C. -2
  4. D. 19

Correct answer: C. -2

i × j is a multiple of 3 only when i = 3 or j = 3. Row i = 3 adds 3 × 4 = 12, and column j = 3 for i = 1, 2, 4 adds 7, so +19. The other 9 pairs (i, j from {1, 2, 4}) subtract j: 3 × (1 + 2 + 4) = 21. 19 - 21 = -2.

More Pseudocode and Code Tracing questions

Exams that ask this topic