ProgrammingHardIBM · Deloitte pattern

Assume 32-bit int. What is printed?

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

Correct answer: A. 16

This loop checks and discards the lowest bit one at a time (x & 1, then x >>= 1), counting the number of 1 bits (popcount) in 0xF0F0F0F0. Each hex digit F (1111) contributes 4 set bits, and there are 4 F digits, giving 4*4 = 16 set bits total.

More C Programming questions

Exams that ask this topic