ProgrammingModerateCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    int total = 0;
    for (unsigned x = 1; x <= 100; x++) {
        unsigned y = x;
        while (y) {
            total += y & 1u;
            y >>= 1;
        }
    }
    printf("%d", total);
}
  1. A. 316
  2. B. 580
  3. C. 319
  4. D. 350

Correct answer: C. 319

The inner loop adds one per set bit, and the set bits of 1..100 total 319 (1..63 hold 6 x 32 = 192, and 64..100 add 127). 316 stops at 99 and misses the three bits of 100, 580 counts every inner-loop pass (bit lengths) rather than set bits, and 350 assumes half of 7 bit positions are set.

More C Programming questions

Exams that ask this topic