C Program to convert decimal number to binary

Problem

Write a program in C to convert a decimal number to binary number

How to convert a decimal number to binary number in C ?

#include <stdio.h>
#include <math.h>
long DecimalToBinary(int n);

int main()
{
    int input;
    printf("Abundantcode.com Coding samples\n");
    printf("Enter a decimal number: ");
    scanf("%d", &input);
    printf("%ld",DecimalToBinary(input));
    return 0;
}

long DecimalToBinary(int n)
{
    long binaryNumber = 0;
    int remainder, i = 1, step = 1;

    while (n!=0)
    {
        remainder = n%2;
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}

Output

Abundantcode.com Coding samples                   
Enter a decimal number: 10                                    
1010

Tags :

Leave Your Comment

Liked this content?. Please spread the word :)