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);
}- A. 316
- B. 580
- C. 319
- 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
- What is printed? c #include <stdio.h> #include <string.h> int main(void) { const char names[] = {"ann", "bob", "cat", "dan", "eve"}; const…
- What is printed? Assume long long is 64 bits and that the product fits in a long long. c #include <stdio.h> int main(void) { long long p =…
- What is printed? c #include <stdio.h> int clz16(unsigned short x) { int n = 0; while (!(x & 0x8000u)) { x <<= 1; n++; } return n; } int…
- What is printed? Assume ASCII character encoding. c #include <stdio.h> int main(void) { int d = 'z' - 'a'; char e = 'A' + d 2; printf("%d…
- What is printed? c #include <stdio.h> int main(void) { int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; int (p)[3] = m; int q = (int )p + 4…
- What is printed? Assume unsigned short is 16 bits. c #include <stdio.h> int main(void) { unsigned short y = 60000; y += 10000…