Saturday, June 18, 2016

C Program Code: Convert Decimal to Binary

C Program Code:

#include<stdio.h>
void decimalToBinary(int number, int base);
int main()
{
    int decimalNumber = -1;
    int base = 2;   // Base of Binary Number is 2
    printf("Decimal to Binary Converter in C \n");
    printf("Enter number in decimal: ");
    scanf("%d", &decimalNumber);
    if (decimalNumber < 0)
    {
        printf("Invalid Input, Please Enter a Positive Number \n");
        printf("Press enter to continue... \n");
        getchar();
        return 0;
    }
    printf("Decimal %d = ", decimalNumber);
    decimalToBinary(decimalNumber, base);
    printf(" Binary \n");
    printf("Press enter to continue... \n");
    fflush(stdin);
    getchar();
    return 0;
}
void decimalToBinary(int number, int base)
{
    if (number > 0)
    {
        decimalToBinary(number / base, base);
        printf("%d", number%base);
    }
}

Convert Decimal to Binary in C Language Recursive Output Screenshot