ProgrammingVery hardProduct company OA

What will be the output of the following pseudocode? (&, |, ^ are bitwise AND, OR, XOR; << is a left shift.)

What will be the output of the following pseudocode? (&, |, ^ are bitwise AND, OR, XOR; << is a left shift.)
Integer x = 0
for (i = 0 to 7)
    if (i & 1)
        x = x | (1 << i)
    else
        x = x ^ (1 << (7 - i))
    end if
end for
Print x
  1. A. 170
  2. B. 255
  3. C. 130
  4. D. 160

Correct answer: D. 160

Odd i OR in bits 1, 3, 5, 7; even i TOGGLE bits 7, 5, 3, 1 – the same bits, so order matters. i0: toggle bit 7 → 128; i1: set bit 1 → 130; i2: toggle bit 5 → 162; i3: set bit 3 → 170; i4: toggle bit 3 OFF → 162; i5: set bit 5 (already on) → 162; i6: toggle bit 1 OFF → 160; i7: set bit 7 (already on) → 160. 170 is the value after i = 3; treating every step as OR gives 170 too.

More Pseudocode and Code Tracing questions

Exams that ask this topic