ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (^ is bitwise XOR and >> is a right shift.)
What will be the output of the following pseudocode? (^ is bitwise XOR and >> is a right shift.)
Integer g = 59, n = 0
while (g > 0)
n = n ^ g
g = g >> 1
end while
Print n- A. 45
- B. 59
- C. 29
- D. 54
Correct answer: A. 45
n becomes g ^ (g >> 1) ^ (g >> 2) ^ …, which decodes a Gray code: each bit of n is the XOR of all bits of g at or above it. g = 59 = 111011. From the top: 1, 1⊕1 = 0, 0⊕1 = 1, 1⊕0 = 1, 1⊕1 = 0, 0⊕1 = 1 → 101101 = 45. (Check: 45 ^ (45 >> 1) = 101101 ^ 010110 = 111011 = 59.) 29 = 59 >> 1 is only the first shift; 54 comes from XOR-ing just g and g >> 1 and then shifting.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- How many times does the body of this loop run? // c is an 8-bit unsigned integer: it holds 0 to 255 and arithmetic wraps modulo 256…
- What will be the output of the following pseudocode? (/ is integer division.) Integer a = 7, b = 3 a = a b - a / b Print a
- What will be the output of the following pseudocode? Integer c = 0 for (i = 1 to 20) if (i mod 3 == 0 or i mod 5 == 0) c = c + 1 end if…
- What will be the output of the following pseudocode? (/ is integer division.) Integer n = 2405, c = 0, s = 0 while (n > 0) s = s + n mod…
- What will be the output of the following pseudocode? Integer c = 0 for (i = 1 to 4) for (j = 1 to 4) if (j > i) break end if c = c + j end…
- What will be the output of the following pseudocode? (&, |, ^ are bitwise AND, OR, XOR; << is a left shift; precedence as in C: << binds…