ProgrammingHardCompetitive coding (CP)
How many values of n in 1..50 have bit 2 set (the value 4)? Compute with this program.
How many values of n in 1..50 have bit 2 set (the value 4)? Compute with this program.
#include <stdio.h>
int main(void) {
int c = 0;
for (unsigned n = 1; n <= 50; n++)
if ((n >> 2) & 1u) c++;
printf("%d", c);
}- A. 12
- B. 47
- C. 24
- D. 25
Correct answer: C. 24
(n >> 2) & 1 tests bit 2, which is set in the runs 4-7, 12-15, ..., 44-47: six runs of four, 24 values (49 and 50 have it clear). 12 counts multiples of 4, 47 drops the & 1 and counts every n >= 4, and 25 wrongly adds 49 or 50.
More C Programming questions
- What is printed? Assume int is 4 bytes. c #include <stdio.h> int main(void) { int m[4][5]; printf("%zu %zu", sizeof m / sizeof m[0]…
- What is printed? Assume unsigned int is 32 bits. c #include <stdio.h> int main(void) { unsigned s = 0; for (unsigned i = 1; i <= 100000…
- How many partitions of 5 are there? The program counts partitions of n into parts of size at most m. Compute with it. c #include <stdio.h>…
- What is printed? c #include <stdio.h> int main(void) { char c = 'A'; c += 32; printf("%c %d", c, c); }
- What is printed? c #include <stdio.h> int main(void) { int x = 2, r = 0; switch (x) { case 1: r += 1; case 2: r += 10; case 3: r += 100…
- How many loop iterations run? Compute with the program. c #include <stdio.h> int main(void) { unsigned x = 0xF00D; int c = 0; while (x) {…