ProgrammingHardInfosys SP · Cognizant GenC Next

What will be the output of the following pseudocode? (mod is applied to (i j) before adding)

What will be the output of the following pseudocode? (mod is applied to (i * j) before adding)
Integer x = 0
for (each i from 1 to 5)
    for (each j from i to 5)
        x = x + (i * j) mod 3
    end for
end for
Print x
  1. A. 18
  2. B. 24
  3. C. 15
  4. D. 14

Correct answer: D. 14

(i × j) mod 3 is 0 whenever i or j is 3; otherwise it is 1 if i and j have the same remainder mod 3 and 2 if not. Row by row (j from i to 5): i = 1 gives 1 + 2 + 0 + 1 + 2 = 6, i = 2 gives 1 + 0 + 2 + 1 = 4, i = 3 gives 0, i = 4 gives 1 + 2 = 3, i = 5 gives 1. Total 14.

More Pseudocode and Code Tracing questions

Exams that ask this topic