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 the Decimal Number to Binary Number – First, Divide the Original value by 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

 #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 Example

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 another example of converting the decimal values to binary numbers, and for this, we are using a while loop.

 #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;
}

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.

 #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;
}

Decimal to Binary output


 Please Enter the Number You want to Convert  :  32
00000000000000000000000000100000