ProgrammingVery hardGATE CS · Competitive coding (CP)

What is printed?

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

Correct answer: A. 4

Simulating the bitwise addition of 1011 and 0111 gives carries out of bit positions 0, 1, 2 and 3, so four carries occur. The loop counts carries, not the sum bits.

More C Programming questions

Exams that ask this topic