C Program to convert Decimal to Binary

Decimal to binary in C: We can convert any decimal number (base-10 (0 to 9)) into binary number(base-2 (0 or 1)) by c program.

Decimal Number

Decimal number is a base 10 number because it ranges from 0 to 9, there are total 10 digits between 0 to 9. Any combination of digits is decimal number such as 23, 445, 132, 0, 2 etc.

Binary Number

Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is binary number such as 1001, 101, 11111, 101010 etc.

To understand this example, you should have the knowledge of the following C programming topics:

C Functions
C User-defined functions

Decimal to Binary Conversion Algorithm

Step 1: Divide the number by 2 through % (modulus operator) and store the remainder in array
Step 2: Divide the number by 2 through / (division operator)
Step 3: Repeat the step 2 until number is greater than 0
Let’s see the c example to convert decimal to binary.

#include<stdio.h>

int main()
{
    int a[10],n,i;
    printf("Enter the number to convert: ");
    scanf("%d",&n);
    for(i=0;n>0;i++)
    {
        a[i]=n%2;
        n=n/2;
    }
    printf("\nBinary of Given Number is=");
    for(i=i-1;i>=0;i--)
    {
        printf("%d",a[i]);
    }
    return 0;
}

Output:

Ex:1
Enter the number to convert: 15

Binary of Given Number is=1111

Ex:2
Enter the number to convert: 12

Binary of Given Number is=1100

2nd method

/*Program to convert decimal to binary*/
#include <math.h>
#include <stdio.h>
long long convert(int n);
int main() {
    int n;
    printf("Enter a decimal number: ");
    scanf("%d", &n);
    printf("%d in decimal = %lld in binary", n, convert(n));
    return 0;
}

long long convert(int n) {
    long long bin = 0;
    int rem, i = 1, step = 1;
    while (n != 0) {
        rem = n % 2;
        printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, rem, n / 2);
        n /= 2;
        bin += rem * i;
        i *= 10;
    }
    return bin;
}

Output:

Enter a decimal number: 15
Step 1: 15/2, Remainder = 1, Quotient = 7
Step 2: 7/2, Remainder = 1, Quotient = 3
Step 3: 3/2, Remainder = 1, Quotient = 1
Step 4: 1/2, Remainder = 1, Quotient = 0
15 in decimal = 1111 in binary

Programming Solutions @ rajeshshukla

All Programs
C Language Simple Programs
C Language If Condition and Switch Statement Programs
C Language Loop Programs
C Language Conversion Programs
C Language Pattern Programs
C Language Single Dimension Numeric Array programs
C Language Double Dimension Numeric Array Programs
C Language Single Dimension Character Array programs
C Language Pointer Programs
C Language File Handling Programs

Tutorials

Technical Questions

Interview Questions

C Programming
C++ Programming
Class 11 (Python)
Class 12 (Python)
C Language
C++ Programming
Python

C Interview Questions
C++ Interview Questions


Number Of Visitors

0125622