Monday, 24 July 2017

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

This C Program converts a decimal number into binary & count the number of 1s. The program uses module operation and multiplication with base 2 operation for conversion. It also uses modulo operation to check for 1’s and accordingly increments the count of 1s.
Here is source code of the C program to convert a decimal number to binary & count the number of 1s. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C program to accept a decimal number and convert it to binary
  3.  * and count the number of 1's in the binary number
  4.  */
  5. #include <stdio.h>
  6.  
  7. void main()
  8. {
  9.     long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0;
  10.  
  11.     printf("Enter a decimal integer \n");
  12.     scanf("%ld", &num);
  13.     decimal_num = num;
  14.     while (num > 0)
  15.     {
  16.         remainder = num % 2;
  17.         /*  To count no.of 1s */
  18.         if (remainder == 1)
  19.         {
  20.             no_of_1s++;
  21.         }
  22.         binary = binary + remainder * base;
  23.         num = num / 2;
  24.         base = base * 10;
  25.     }
  26.     printf("Input number is = %d\n", decimal_num);
  27.     printf("Its binary equivalent is = %ld\n", binary);
  28.     printf("No.of 1's in the binary number is = %d\n", no_of_1s);
  29. }
$ cc pgm46.c
$ a.out
Enter a decimal integer
134
Input number is = 134
Its binary equivalent is = 10000110
No.of 1's in the binary number is = 3

No comments:

Post a Comment