We need to write a program in C to convert a decimal number into a binary number.

Example:

decimal to binary

The approach is the same as depicted in the above diagram. we need to divide the dividend (i.e decimal) until it reduces to 0 and concatenate and output the remainder (binary) in a bottom-up manner (i.e from last to first).

To achieve the remainder in the bottom-up manner we need to concatenate each of the upcoming remainders to the left of the concatenated binary number. For this, we will need to first multiply equal number 10 to the remainder as the number of digits already present in the concatenated binary number and then add to the concatenated binary number.

Convert Decimal to Binary in C using While Loop

Output

decimal to binary c output

Convert Decimal to Binary in C using Recursion

In this method, on each recursive we are passing quotient (e.g 15/2 = 7) and since recursion implements stack so the remainder (e.g 15%2 = 1) will start getting printed from the last recursive call. Therefore it automatically implements the bottom-up approach.

Output

decimal to binary c output

If you have any suggestion or doubts then comment below.

Leave a Reply

Close Menu