ProgrammingVery hardCompetitive coding (CP)

How many times does the loop body run?

How many times does the loop body run?
#include <stdio.h>
int main(void) {
    unsigned mask = 0x2D, n = 0;
    for (unsigned s = mask; s; s = (s - 1) & mask)
        n++;
    printf("%u", n);
}
  1. A. 16
  2. B. 14
  3. C. 15
  4. D. 32

Correct answer: C. 15

The loop visits every non-empty submask of 0x2D, which has four set bits, so 2^4 - 1 = 15 submasks. The zero submask is excluded because the loop stops at s = 0.

More C Programming questions

Exams that ask this topic