Q:

# C program to count number of bits set to 1 in an Integer

Write a C program to count number of bits set to 1 in an Integer.

Pre-requisite: Input number n

Algorithm:

```1)  Set count=1

2)  Do bit wise AND with n and 1.
n & 1

let n be a7a6a5a4a3a2a1a0
1->00000001
So doing bitwise AND (refer to published article on bitwise operators)
will result in all bits 0 except the LSB which will be a0.
If a0 is 0 then the all bits are not set
Thus,
IF
n& 1 == 1
count++;
END IF
Right shift n by 1
n=n>>1

3)  IF n==0
Print count
ELSE
REPEAT step 1, 2
```

Example with Explanation:

```Checking for 7
7->00000111

Initially, count=0

So first iteration:
n=7 //00000111
n & 1 =1
so , count=1
n=n>>1 (n=3) //00000011

So second iteration:
n=3 //00000011
n & 1 =1
count=2
n=n>>1 (n=1) //00000001

So third iteration:
n=1 //00000001
n & 1 =1
count=3
n=n>>1 (n=0) //00000000
So, Print count, 3```

C implementation

``````#include <stdio.h>

int main()
{
unsigned int n;
printf("enter the integer\n");
scanf("%d",&n);

int count=0;

while(n!=0){
if(n & 1 == 1){ //if current bit 1
count++;//increase count
}
n=n>>1;//right shift
}

printf("no of bits those are 1 ");
printf("in its binary representation: %d\n",count);

return 0;
}``````

Output

```First run:
enter the integer
7
no of bits those are 1 in its binary representation: 3

Second run:
enter the integer
12
no of bits those are 1 in its binary representation: 2```