Index « Previous Next »

Question

Write a program that prompts the user to input a decimal integer and display its binary equivalent.

Source Code

#include <stdio.h>

int main()
{
    int number, n, remainder, binary = 0, place = 1;

    printf("Enter a number :");
    scanf("%d", &number);

    n = number;

    while (n > 0)
    {
        remainder = n % 2;
        binary += remainder * place;
        place *= 10;
        n /= 2;
    }
    
    printf("Binary equivalent of %d is %d", number, binary);

    return 0;
}

Output

Enter a number :12
Binary equivalent of 12 is 1100