C Program to convert decimal number to binary


This content was proof-read by Grammarly. You can Try Grammary for FREE

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

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: