C Programming - Bitwise Operators - Discussion

Discussion Forum : Bitwise Operators - Point Out Correct Statements (Q.No. 2)
2.
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;
}
It counts the number of bits that are ON (1) in the number num.
It counts the number of bits that are OFF (0) in the number num.
It sets all bits in the number num to 1
Error
Answer: Option
Explanation:

If we give input 4, it will print 1.
Binary-4 == 00000000 00000100 ; Total number of bits = 1.

If we give input 3, it will print 2.
Binary-3 == 00000000 00000011 ; Total number of bits = 2.

If we give input 511, it will print 9.
Binary-511 == 00000001 11111111 ; Total number of bits = 9.

Discussion:
12 comments Page 2 of 2.

Pavan said:   5 years ago
T+=i&1 is same as T=T+(i&1) i.e,adding result (i&1) to initial value of T and again storing it in T.

Sibysagar said:   3 years ago
@Aami.

As we num>>=1 right shift the value of num, when it reaches binary value 0000000000000000 it gets out of for loop.

If we give num=4;
then the loop runs for 3 three times and the num value will be;

1st time entering loop num will be 4 (0000000000000100) after the right shift it will be(0000000000000010).

2nd time entering loop num will be 2 (0000000000000010) after the right shift it will be(0000000000000001).

3rd time entering loop num will be 1 (0000000000000001) after the right shift it will be (0000000000000000).

4th time entering loop num will be 0 (0000000000000000) so code will exit for a loop.


Post your comments here:

Your comments will be displayed after verification.