ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    int s = 0;
    for (unsigned i = 0; i < 8; i++)
        s += (i ^ (i >> 1)) & 1u;
    printf("%d", s);
}
  1. A. 4
  2. B. 3
  3. C. 2
  4. D. 5

Correct answer: A. 4

The lowest bit of the Gray code of i is set for 4 of the 8 values, since the Gray code's bit 0 equals bit 0 XOR bit 1 of i. So the sum is 4.

More C Programming questions

Exams that ask this topic