C Program to count zeros and ones in a binary number

0

Method 1

#include <stdio.h>
 
#define INT_SIZE sizeof(int) * 8 /* Total number of bits in integer */
 
int main()
{
    int num, zeros, ones, i;
     
    printf("Enter any number: ");
     
    scanf("%d", &num);
 
    zeros = 0;
     
    ones = 0;
     
    for(i=0; i<INT_SIZE; i++)
     
    {
    /* If Left Shift Bit is set then increment ones*/
        if(num & 1)
      
            ones++;
      
        else
      
            zeros++;
 
        /* Right shift bits of num to one position */
      
        num >>= 1;
    }
 
    printf("Total zero bit is %d\n", zeros);
     
    printf("Total one bit is %d", ones);
 
    return 0;
}

Output

Enter any number: 22
Total zero bit is 29
Total one bit is 3

Leave a Reply

Your email address will not be published. Required fields are marked *