C Program to Convert Decimal to Binary

Conversion Between Binary and Decimal

The programs to convert decimal to binary have been shown here.






1. C Program to convert decimal to binary

Code has been copied
/*************************************
    	alphabetacoder.com
C program to convert decimal to binary
**************************************/

#include <stdio.h>

int main() {
    // declare variables
    long num;
    int bin[31] = {0};
    int i, n = 0;

    // take input
    printf("Enter the number in decimal: ");
    scanf("%ld", & num);

    // convert the number in binary
    //store the result in an array
    // binary number would be stored
    // in reverse order 
    while (num > 0) {
        bin[n] = num % 2;
        n++;
        num = num / 2;
    }

    // display the number in binary
    printf("Binary: ");
    for (i = n - 1; i >= 0; i--) {
        printf("%d", bin[i]);
    }

    // new line
    printf("\n");

    return 0;
}

Output


Case 1:

Enter the number in decimal: 77

Binary: 1001101


Case 2:

Enter the number in decimal: 9

Binary: 1001





2. C Program to convert decimal to binary using recursion

Code has been copied
/****************************
    alphabetacoder.com
C program to convert decimal
to binary using recursion
*****************************/

#include <stdio.h>

// function to display  
// decimal to binary
void decimal_to_binary(long num) {
    if (num > 1) {
        // call the function
        decimal_to_binary(num / 2);
    }
    // display binary digit
    printf("%ld", num % 2);
}

int main() {
    // declare variables
    long num;

    // take input
    printf("Enter the number in decimal: ");
    scanf("%ld", & num);

    printf("Binary: ");
    // call function to display 
    // the decimal number in binary
    // display the number in binary
    decimal_to_binary(num);

    // new line
    printf("\n");

    return 0;
}

Output


Case 1:

Enter the number in decimal: 77

Binary: 1001101


Case 2:

Enter the number in decimal: 9

Binary: 1001