Here's a C program to convert a decimal number to a binary number with output and proper explanation. This program makes use of C concepts like For loop, While loop, Arrays and Modulus.

# include <stdio.h> # include <conio.h> void main() { long b[20], n, r, c = 0, i ; clrscr() ; printf("Enter a decimal number : ") ; scanf("%ld", &n) ; while(n > 0) { r = n % 2 ; b[c] = r ; n = n / 2 ; c++ ; } printf("\nThe binary equivalent is : "); for(i = c - 1 ; i >= 0 ; i--) printf("%ld", b[i]) ; getch() ; }

**Output of above program is**

Enter a decimal number : 18

The binary equivalent is : 10010

How to convert Decimal Number to Binary form?The basic method for this conversion is -

- Divide the decimal number by 2. Note only the integer part of quotient. Also note down the remainder i.e. if the number is divisible by 2 then 0 otherwise 1.
- Repeat the above step for every quotient until the quotient becomes 0.
- When quotient becomes zero read the remainders in reverse direction to get the binary form of your number.

Decimal to Binary Conversion |

**Explanation of above program**

First take a look at all the variables. All variables are of Long Data Type-

- n - is the number that user enters.
- b[20] - is an array of size 20 and is used to store the remainders obtained along the calculation. To obtain the binary number once the calculation is finished we just have to reverse this array.
- r - is used to store the remainder temporarily.
- i - is the loop variable.
- c - is a counter variable which is initialized to zero at the start of the program.

First we ask the user to enter a number. Then using while loop we are calculating the remainders and storing it in the array b[20]. After that using for loop we reverse our array and finally prints the binary equivalent of the entered number.

Suppose, n = 18 -

**Working of while loop -**

**n > 0 i.e. 18 > 0. While loop is executed -**

- r = n % 2 = 18 % 2 = 0.
- b[c] = r or b[0] = 0.
- n = n / 2 or n = 18 / 2 = 9.
- c++ or c = 1.

**n > 0 i.e. 9 > 0. While loop is executed -**

- r = n % 2 = 9 % 2 = 1.
- b[c] = r or b[1] = 1.
- n = n / 2 or n = 9 / 2 = 4. (only integer part)
- c++ or c = 2.

**n > 0 i.e. 4 > 0. While loop is executed -**

- r = n % 2 = 4 % 2 = 0.
- b[c] = r or b[2] = 0.
- n = n / 2 or n = 4 / 2 = 2.
- c++ or c = 3.

**n > 0 i.e. 2 > 0. While loop is executed -**

- r = n % 2 = 2 % 2 = 0.
- b[c] = r or b[3] = 0.
- n = n / 2 or n = 2 / 2 = 1.
- c++ or c = 4.

**n > 0 i.e. 1 > 0. While loop is executed -**

- r = n % 2 = 1 % 2 = 1.
- b[c] = r or b[4] = 1.
- n = n / 2 or n = 1 / 2 = 0.
- c++ or c = 5.

- n = 0.
- c = 5.
- b[0] = 0, b[1] = 1, b[2] = 0, b[3] = 0 and b[4] = 1