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

**Example:**

1 2 3 4 5 | Input: 5 Output: 101 Input: 15 Output: 1111 |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> #include <stdlib.h> int main() { int n, binary=0, rem, i=1; //Input the decimal number printf("Enter a Decimal number \n"); scanf("%d",&n); //While loop will run until n becomes by dividing it by 2 while(n != 0) { rem = n%2; binary = (rem*i) + binary; //adding the remainder on left of binary n = n/2; i= i*10; //update i, so that on next iteration, // rem will be added to left of binary } printf("Binary: %d", binary); return 0; } |

**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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> #include <stdlib.h> void decToBin(int n){ if(n > 0){ //recall by passing quotient decToBin(n/2); //print remainder printf("%d",n%2); } } int main() { int n; //Input the decimal number printf("Enter a Decimal number \n"); scanf("%d",&n); printf("Binary: "); decToBin(n); return 0; } |

**Output**

If you have any suggestion or doubts then comment below.