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

Example:

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.

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.

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

1 − one =