Friday 5 January 2018

Decimal number and convert it to binary and count the number of 1's in the binary number in C

/*
 * C program to accept a decimal number and convert it to binary
 * and count the number of 1's in the binary number
 */
#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);
}


convert the given binary number into decimal in c

/*
 * C program to convert the given binary number into decimal
 */
#include <stdio.h>

void main()
{
    int  num, binary_val, decimal_val = 0, base = 1, rem;

    printf("Enter a binary number(1s and 0s) \n");
    scanf("%d", &num); /* maximum five digits */
    binary_val = num;
    while (num > 0)
    {
        rem = num % 10;
        decimal_val = decimal_val + rem * base;
        num = num / 10 ;
        base = base * 2;
    }
    printf("The Binary number is = %d \n", binary_val);
    printf("Its decimal equivalent is = %d \n", decimal_val);
}