ProgrammingModerateAccenture · Cognizant pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer x = 0
for (each i from 1 to 5)
    for (each j from 1 to i)
        if ((i + j) mod 2 == 0)
            x = x + j
        end if
    end for
end for
Print x
  1. A. 15
  2. B. 19
  3. C. 22
  4. D. 35

Correct answer: C. 22

i + j is even only when j has the same parity as i. i = 1 adds 1, i = 2 adds 2, i = 3 adds 1 + 3 = 4, i = 4 adds 2 + 4 = 6, i = 5 adds 1 + 3 + 5 = 9. Total 22. Adding every j gives the trap 35.

More Pseudocode and Code Tracing questions

Exams that ask this topic