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 1 of 2.

Saurabh said:   1 decade ago
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:   1 decade ago
If num>>1 means right shift one bit, but what is mean by num>>=1 ?

Spa said:   1 decade ago
@vijay yes i too have d same doubt.
what is mean by num>>=1 ?

Varun said:   1 decade ago
I think it is short hand operator such that num=num>>1 ?

Kadarkarai Selvam said:   1 decade ago
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:   1 decade ago
What is the meaning of if(num&1)?

Lohith said:   1 decade ago
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:   9 years ago
No termination condition for FOR LOOP? Will it runs infinitely.

Mihir said:   9 years ago
Thanks @Kadarkarai Selvam.

Suheel said:   6 years ago
What "T+=i&1;" means?


Post your comments here:

Your comments will be displayed after verification.