C Programming - Bitwise Operators - Discussion

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;
}

[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: Option A

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.


Saurabh said: (Jan 21, 2011)  
The answer is A. Let binary value of num is 10101 then the loop checks each bit on by 'if(num & 1)' and num>>=1 right shifts the num bits by 1bit

Vijay said: (Aug 3, 2012)  
If num>>1 means right shift one bit, but what is mean by num>>=1 ?

Spa said: (Aug 18, 2012)  
@vijay yes i too have d same doubt.
what is mean by num>>=1 ?

Varun said: (Aug 22, 2012)  
I think it is short hand operator such that num=num>>1 ?

Kadarkarai Selvam said: (Sep 14, 2012)  
Let us take num=20
Here num>>=1 means that num=num>>1
In for loop,
At num =20 ie 0001 0100
Now num&1 gives 000000 so it wont increment c

Then at next loop,
num= num>>1 ie 0000 1010
Now num&1 gives 0000 0000 so it wont increment c

Then at next loop,
num= num>>1 ie 0000 0101
Now num&1 gives 0000 0001 so it increment c

Like that it goes and c increments for 2 times in this case..
Thus it gives the number of ON bits in num..

Ash said: (Mar 15, 2014)  
What is the meaning of if(num&1)?

Lohith said: (Aug 18, 2015)  
Num &1 means doing AND operation for num and 1 for example.

Num = 0010(2).

1 = 0001.
-----------.
0000 (Here c will no increment and goes to for loop).

For next loop right bit shift was implemented.

Num = 0001(2).

1 = 0001.
-----------.
0001 (here c will be increment and goes to for loop).

This process was continued up to num times.

if (0)
{
Terminated the if condition and goes to for loop.
}
if (1)
{
Execute the if condition.
}

Aami said: (Mar 4, 2016)  
No termination condition for FOR LOOP? Will it runs infinitely.

Mihir said: (Aug 16, 2016)  
Thanks @Kadarkarai Selvam.

Suheel said: (Jan 28, 2020)  
What "T+=i&1;" means?

Pavan said: (Sep 3, 2020)  
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.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.