Summary: In this programming example, we will learn to convert a decimal number into its binary representation in C using loop and recursion.

Example:

Input:  5
Output: 101

Input:  15
Output: 1111

Method 1: Using While Loop

decimal to binary

We repeatedly divide the decimal number by 2 until it reduces to 0 and concatenate all the remainders in a bottom-up manner to get the binary corresponding of the given number.

#include <stdio.h>
 
int main()
{
 
    int n, binary=0, rem, i=1;
 
    //Input the decimal number
    printf("Enter a decimal number: \n");
    scanf("%d",&n);
 
    //loop until number reduces to 0
    while(n != 0)
    {   
        //get the remainder
        rem = n%2;
        
        //concatenate the remainder to binary number
        binary = (rem*i) + binary;       
        
        //adding the remainder on left of binary
        n = n/2;
        
        //update i
        i= i*10;                         
    }
 
    printf("Binary: %d", binary);
 
    return 0;
}

Output:

Enter a decimal number:
15
Binary: 1111


In the above program, we have implemented the above-mentioned process (i.e. divide and stack the remainders in a bottom-up manner) inside a while loop.

We are concatenating each remainder value to the left of the binary number. To do this we multiply an equal number of 10 to the remainder as the number of digits already present in the concatenated binary number and then add the result to the binary variable.

Method 2: Using Recursion

We can also convert a decimal into binary using recursion.

The approach is same as the above program but is implemented in a recursive way.

#include <stdio.h>
 
//recursive function
void decToBin(int n){
    
    if(n>0){
        //recusive call by passing the quotient value
        decToBin(n/2);
        
        //print the remainder during traceback
        printf("%d",n%2);
    }
}
 
int main()
{
    int n;
 
    printf("Enter a Decimal number: \n");
    scanf("%d",&n);
    
    //call the recusive function to print the corresponding binary
    printf("Binary: ");
    decToBin(n);
 
    return 0;
}

Output:

Enter a Decimal number:
5
Binary: 101


In this method, we have used the head recursion approach. Because of this, the remainders begin to output from the final recursive call (i.e. bottom-up manner), hence forming the corresponding binary number.

In every successive recursive call, we are passing quotient (i.e. 15/2 = 7) as an argument for further processing.

These are the two ways using which we can convert any decimal number into its corresponding binary representation in the C programming language.

Leave a Reply