This is a C Program to count number of bits set to 0 in an integer.
This C Program counts number of bits set to 0 in a integer x.
Take input from the user and performs bits operations as shown in the program below.
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; }
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.
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.
$ 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
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Buy Computer Science Books
- Practice BCA MCQs
- Apply for C Internship