ProgrammingHardGATE CS · TCS NQT

What is printed?

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

Correct answer: B. 3

The Gray codes for i = 0 to 7 are 0, 1, 3, 2, 6, 7, 5, 4, and the ones with exactly two set bits are 3, 6 and 5. Counting i instead of the Gray value gives a different answer.

More C Programming questions

Exams that ask this topic