C Program to convert a decimal number to a binary number

The following is a C program to convert a decimal number to a binary number:

Expected Output:

1sr run:

2nd run:

How it works:

To convert a decimal number to a binary number, we follow these steps:

Step 1: Divide the decimal number continuously by 2 and right the remainder on the right-hand side of the dividend. We repeat this process until we get the quotient 0.

Step 2: Write the remainders from bottom to top.

Let’s take some examples now:

Example 1: Convert decimal number 5 to a binary.

Step 1:

Quotient Remainder
5/2 2 1
2/2 1 0
1/2 0 1

Step 2:

510 =  1012

Example 2: Convert decimal number 123 to a binary.

Step 1:

Quotient Remainder
123/2 61 1
61/2 30 1
30/2 15 0
15/2 7 1
7/2 3 1
3/2 1 1
1/2 0 1

Step 2:

12310 =  11110112

The following table shows what happens at each iteration of the loop (assuming num = 4):

Iteration rem bin num i
After 1st iteration rem = 4 % 2 = 0 bin = 0 * (10^0) + 0 = 0 num = 4 / 2 = 2 i = 2
After 2nd iteration rem = 2 % 2 = 0 bin = 0 * (10^1) + 0 = 0 num = 2 / 2 = 1 i = 3
After 3rd iteration rem = 1 % 2 = 1 bin = 1 * (10^2) + 0 = 100 num = 1 / 2 = 0 i = 4

 

Leave a Comment

%d bloggers like this: