C Program to Convert Decimal to Binary

How to write a C Program to Convert Decimal to Binary Number with a practical example?. To convert Decimal Number to Binary Number in C – First, Divide Original value with 2. Next, Divide the Quotient by 2. Repeat the same steps until the given number is zero.

C Program to Convert Decimal to Binary Example

This program to convert decimal to binary uses For Loop to convert the user given Decimal value to Binary value

/* C Program to Convert Decimal to Binary */
 
#include <stdio.h>
int main() 
{
    int a[10], number, i, j;
    printf("\n Please Enter the Number You want to Convert  :  ");
    scanf("%d", &number);
    
    for(i = 0; number > 0; i++)
    {
        a[i] = number % 2;
        number = number / 2;
    }
    
    printf("\n Binary Number of a Given Number =  ");
    for(j = i - 1; j >= 0; j--)  {
        printf(" %d ", a[j]);
    }
    printf("\n");
    return 0;
}
C Program to Convert Decimal to Binary 1

Within this program to convert decimal to binary, first, we used For Loop. Here, number = 5

Loop First Iteration: for(i = 0; Number > 0; i++)
for(i = 0; 5 > 0; 0++) – condition true
a[0] = number % 2 => 5 % 2 = 1
number = number / 2 = 2.5

Second Iteration: for(i = 1; 2 > 0; 1++)
a[1] = 2.5 % 2 = 0
number = 2.5 / 2 = 1.25

Third Iteration: for(i = 2; 1 > 0; 2++)
a[2] = 1.25 % 2 = 1
number = 0

Next, we used the C Programming For Loop to Print Array elements.

Convert Decimal to Binary using While loop

This is an another C example to convert the decimal values to binary numbers, and for this, we are using while loop.

/* C Program to Convert Decimal to Binary */
 
#include <stdio.h>
 
int main() 
{
    int a[10], number, i = 1, j;
    printf("\n Please Enter the Number You want to Convert  :  ");
    scanf("%d", &number);
    
    while(number  != 0)
    {
        a[i++] = number % 2;
        number = number / 2;
    }
    
    printf("\n Binary Number of a Given Number =  ");
    for(j = i - 1; j > 0; j--)  {
        printf(" %d ", a[j]);
    }
    return 0;
}

C Decimal to Binary output


 Please Enter the Number You want to Convert  :  25

 Binary Number of a Given Number =   1  1  0  0  1 

C Program to Convert Decimal to Binary using Functions

In this program, we used Functions and Bitwise AND Operator to convert decimal values to binary.

/* C Program to Convert Decimal to Binary */
 
#include <stdio.h>

void Decimal_to_Binary(int number)
{
    int j;
    for(int i = 31; i >= 0; i--)
    {
        j = number >> i;
        
        if(j & 1)
            printf("1");
        else
            printf("0");
    }
}
int main() 
{
    int number;
    
    printf("\n Please Enter the Number You want to Convert  :  ");
    scanf("%d", &number);
    
    Decimal_to_Binary(number); 
            
    return 0;
}

C Decimal to Binary output


 Please Enter the Number You want to Convert  :  32
00000000000000000000000000100000