ProgrammingHardWipro · Cognizant pattern

Assume 32-bit int. What is printed?

Assume 32-bit int. What is printed?
int x = 13;
int count = 0;
while (x) {
    count += x & 1;
    x >>= 1;
}
printf("%d", count);
  1. A. 4
  2. B. 3
  3. C. 13
  4. D. 2

Correct answer: B. 3

13 in binary is 1101, which has three set bits. The loop isolates and counts the lowest bit each iteration while right-shifting, so count ends at 3.

More C Programming questions

Exams that ask this topic