Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of the following statements are correct about the program?

#include <stdio.h>

int main()
{
    unsigned int num;
    int c=0;
    scanf("%u", &num);
    for(;num;num>>=1)
    {
        if(num & 1)
            c++;
    }
    printf("%d", c);
    return 0;
}

 

  • A.It counts the number of bits that are ON (1) in the number num.
  • B.It counts the number of bits that are OFF (0) in the number num.
  • C.It sets all bits in the number num to 1
  • D.Error

Answer: A

Correct answer: It counts the number of bits that are ON (1) in the number num.

The loop is the standard population count. Each pass tests the lowest bit with num & 1, incrementing c when it is set, then shifts num right by one so the next bit takes that position.

The loop condition num stops as soon as the value reaches zero, so it runs once per significant bit rather than a fixed number of times. Declaring num unsigned matters: right-shifting a negative signed value propagates the sign bit and the loop would never terminate.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.