Dear Tariq,
I know the source from where you found this program and let me tell you that, those set of books are worst. Now coming to my answer.
That is not surprising of that book it has lots of mistakes. Therefore below is the correct program.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n=10,y;
y=foo(n);
printf("%d",y);
}
int foo(unsigned int n)
{
int x=0;
while(n!=0)
{
if(n&01) x++;
n>>=1;
}
return x;
}
Output: 2
Explanation
First loop:
n=10, now convert it into binary i.e. 1010. now (1010 & 0001) will be 0000. so ultimately 0. False condition.
x will remain 0.
But, n is shift right side by 1 bit i.e. 0101. (in decimal n=5)
Second Loop:
n=5, now again (0101 & 0001) will be 0001. So in decimal 1. Condition Satisfied.
Therefore x will be incremented by 1. (x=1)
n will be shifted by 1 bit. 0010. (in decimal n=2)
Third Loop:
n=2, now convert it into binary i.e. 0010. now (0010 & 0001) will be 0000. so ultimately 0. False condition.
x will remain 1.
But, n is shift right side by 1 bit i.e. 0001. (in decimal n=1)
Fourth Loop:
n=1, now again (0001 & 0001) will be 0001. So in decimal 1. Condition Satisfied.
Therefore x will be incremented by 1. (x=2)
n will be shifted by 1 bit. 0000. (in decimal n=0)
Now, (n!=0) condition is false, hence it goes out of the loop. and return x. which is printed in main().