C Program to Convert a Decimal Number to Binary & Count the Number of 1s

0
number-system-in-c

In the C Program, we will convert a decimal number to binary and while doing that we will count the number of times 1 comes.

In order to do this, we will do the following approach –

  1. Take a decimal integer as input by the user
  2. Using the while loop, we will divide the number by 2
  3. If the remainder is 1 increase the value of no_of_1s by 1.
  4. That’s it. Now will just display the variable data.

In order to understand better, here is your C Program to convert decimal number into binary

#include <stdio.h>
 
void main()
 
{
 
    long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0;
 
    printf("Enter a decimal integer \n");
 
    scanf("%ld", &num);
 
    decimal_num = num;
 
    while (num > 0)
 
    {
 
        remainder = num % 2;
 
        /*  To count no.of 1s */
 
        if (remainder == 1)
 
        {
 
            no_of_1s++;
 
        }
 
        binary = binary + remainder * base;
 
        num = num / 2;
 
        base = base * 10;
 
    }
 
    printf("Input number is = %d\n", decimal_num);
 
    printf("Its binary equivalent is = %ld\n", binary);
 
    printf("No.of 1's in the binary number is = %d\n", no_of_1s);
 
}

Output

Enter a decimal integer
134
Input number is = 134
Its binary equivalent is = 10000110
No.of 1's in the binary number is = 3

Leave a Reply

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