This following program converts a decimal number to a binary number.
To convert a decimal number into binary,we follow the following steps:
Divide the decimal number by 2 and note the remainder
Divide the Quotient repeatedly by 2 and note the remainders till quotient is 0
Write remainder side by side in reverse order to know the binary number
For example 18
18 divide by 2 leaves quotient 9 remainder 0
9 divide by 2 leaves quotient 4 remainder 1
4 divide by 2 leaves quotient 2 remainder 0
2 divide by 2 leaves quotient 1 remainder 0
1 divide by 2 leaves quotient 0 remainder 1
To convert a decimal number into binary,we follow the following steps:
Divide the decimal number by 2 and note the remainder
Divide the Quotient repeatedly by 2 and note the remainders till quotient is 0
Write remainder side by side in reverse order to know the binary number
For example 18
18 divide by 2 leaves quotient 9 remainder 0
9 divide by 2 leaves quotient 4 remainder 1
4 divide by 2 leaves quotient 2 remainder 0
2 divide by 2 leaves quotient 1 remainder 0
1 divide by 2 leaves quotient 0 remainder 1
So binary of 18 is 10010
What happens in the Do While loop:
Step 1. Divide the number in decimal format by 2 and save the remainder in “rem”
Step 2. Place the remainder in the variable sum. We multiply our remainder by “i” so it falls in the right place. i.e, Ones place in 1st time, tens at 2nd and so on.
Step 3. Halve the number in decimal format and save it back to “dec”
Step 4. Multiply “i” by 10 so the next number is placed one place higher in the binary number (i.e, hundreds after tens and thousands after hundreds).
Step 5. Repeat the above steps till decimal number reaches 0