GATE Computer ScienceHardGATE CS

Assume a 32-bit unsigned int. What does the following program print? #include <stdio.h> int main() { unsigned s = 0; for (unsigned i = 1; i <= 1000; i++) s += i & -i; printf("%u", s); }

  1. A. 5050
  2. B. 4950
  3. C. 5060
  4. D. 5120

Correct answer: C. 5060

For unsigned i, −i wraps modulo 2³², so i & −i isolates the lowest set bit of i. Summing the lowest set bit for i = 1 to 1000 gives 5060: each power 2ᵏ is the lowest bit of the numbers 2ᵏ·(odd) up to 1000 and contributes 2ᵏ for each of them.

More Programming and Data Structures (GATE) questions

Exams that ask this topic