ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.)

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.)
Integer n = 6, s = 0
for (each i from 1 to n)
    s = s + (i & 1) * i - (1 - (i & 1)) * i
end for
Print s
  1. A. 21
  2. B. 3
  3. C. 9
  4. D. -3

Correct answer: D. -3

i & 1 is 1 for odd i and 0 for even i, so odd terms are added and even terms subtracted: 1 - 2 + 3 - 4 + 5 - 6 = -3.

More Pseudocode and Code Tracing questions

Exams that ask this topic