Skip to main content

Decimal to binary conversion

Short answer

Divide the decimal number repeatedly by 2, storing remainders in an array; then print remainders in reverse order. For 0, output 0.

Write a program to convert a decimal number into binary number.

Method: divide the number repeatedly by 2 and store the remainders; the binary number is the remainders read in reverse order (last remainder first).

Example, 45: 45/2 = 22 r 1; 22/2 = 11 r 0; 11/2 = 5 r 1; 5/2 = 2 r 1; 2/2 = 1 r 0; 1/2 = 0 r 1. Reading upwards gives 101101.

#include <stdio.h>
int main(void)
{
    int n, i = 0, j, bin[32];
    printf("Enter a decimal number: ");
    scanf("%d", &n);
    if (n == 0)
        bin[i++] = 0;
    while (n > 0)
    {
        bin[i++] = n % 2;     /* remainder is the next bit (LSB first) */
        n = n / 2;
    }
    printf("Binary = ");
    for (j = i - 1; j >= 0; j--)
        printf("%d", bin[j]);
    printf("\n");
    return 0;
}

Output for 45:

Enter a decimal number: Binary = 101101

The remainders are stored in the array bin[] and printed from the last index down to 0.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →