Google News
logo
C Program to Convert Decimal Number to Binary Number
In the following example of C program that converts a decimal number to a binary number :
Program :
#include <stdio.h>

int main() {
    int decimal, binary = 0, place = 1;
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    while (decimal != 0) {
        int digit = decimal % 2;
        binary += digit * place;
        decimal /= 2;
        place *= 10;
    }

    printf("The binary equivalent is %d\n", binary);
    return 0;
}
Output :
Enter a decimal number: 234
The binary equivalent is 11101010
Explanation :

* We start by declaring three variables : decimal to store the decimal number, binary to store the binary equivalent, and place to keep track of the current place value (1, 10, 100, etc.).

* We ask the user to enter a decimal number using printf and scanf.

* We use a while loop to convert the decimal number to binary. The loop continues until the decimal number becomes 0.

* Inside the loop, we get the remainder of the decimal number divided by 2 using the modulo operator %, which gives us the rightmost binary digit. We multiply this digit with the current place value and add it to the binary variable.

* We then divide the decimal number by 2 to remove the rightmost binary digit, and multiply the place variable by 10 to move to the next place value (10, 100, 1000, etc.).

* After the loop, we print the binary variable as the binary equivalent using printf.

Note : This program assumes that the input decimal number is non-negative. If the input is negative, the program may produce unexpected results.