# C Program to Count Set Bits in an Integer

This is a C Program to count number of bits set to 0 in an integer.

Problem Description

This C Program counts number of bits set to 0 in a integer x.

Problem Solution

Take input from the user and performs bits operations as shown in the program below.

Program/Source Code

Here is source code of the C Program to number of bits set to 0 in a integer x. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

```/*
* C Program to Count Number of bits set to 0 in a Integer x
*/
#include <stdio.h>

int main ()
{
int num = 0, i = 0, n = 0, count = 0, zCount = 0;
printf ("Enter the number: ");
scanf ("%d", &num);
n = num;
while (n)
{
count ++;
n = n >> 1;
}
for (i = 0; i < count; i++)
{
if (((num >> i) & 1) == 0)
{
zCount ++;
}
}
printf ("\nNumber of bit's set to zero's are: %d\n", zCount);
return 0;
}```
Program Explanation

1. In this C Program, we are reading the integer number using the ‘num’ variable.
2. While loop is used to count the number of bits in the given number.
3. For loop is used to check each bit whether the bit is set or unset. If the bit is unset it increment the count.
4. Here zCount indicates the number of bits set to 0.
5. Print the number of bits are unset in an integer using printf statement.

Runtime Test Cases

Test case 1 – Here, the entered number is 1.

```\$ gcc count_bits_unset.c -o bits_unset_count
\$ ./bits_unset_count

Enter the number: 1
Number of bit's set to zero's are: 0```

Test case 2 – Here, the entered number is 2.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
```\$ gcc count_bits_unset.c -o bits_unset_count
\$ ./bits_unset_count

Enter the number: 2
Number of bit's set to zero's are: 1```

Test case 3 – Here, the entered number is 7.

```\$ gcc count_bits_unset.c -o bits_unset_count
\$ ./bits_unset_count

Enter the number: 7
Number of bit's set to zero's are: 0```

Test case 4 – Here, the entered number is 8.

```\$ gcc count_bits_unset.c -o bits_unset_count
\$ ./bits_unset_count

Enter the number: 8
Number of bit's set to zero's are: 3```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]