ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (counting trailing zero bits in the binary representation of n)? (All variables are integers, so / is integer division.)

What will be the output of the following pseudocode (counting trailing zero bits in the binary representation of n)? (All variables are integers, so / is integer division.)
Function trailingZeroBits(Integer n)
    Integer c = 0
    while (n mod 2 == 0 and n != 0)
        n = n / 2
        c = c + 1
    end while
    return c
End Function

Print trailingZeroBits(40)
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: B. 3

40 in binary is 101000, which has 3 trailing zero bits (dividing by 2 three times: 40->20->10->5, where 5 is odd).

More Pseudocode and Code Tracing questions

Exams that ask this topic