0% found this document useful (0 votes)
31 views2 pages

Q3. Decimal To Binary

Uploaded by

prafullshyam2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views2 pages

Q3. Decimal To Binary

Uploaded by

prafullshyam2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Decimal to Binary

Problem Description: Given a decimal number (integer N),you have to convert it into binary
and print it. The binary number should be printed in the form of an integer.
For example, if the given decimal number is 12,then the corresponding binary number will be
1100, and we need to print it.

How to approach?
A decimal number can be converted into a binary number by picking up the number and then
taking its remainder, after dividing it by 2, then start adding up the remainder by multiplying it
by its place value to convert the binary representation into an integer.

For example in case of 12, start picking up the remainder when 12 is divided by 2 and then
adding it by multiplying by its place value.
12 = 12%2 = 0*1 = 0
12/2 = 6%2 = 0*10 = 0
6/2 = 3%2 = 1*100 = 100
3/2 = 1%2 = 1*1000 = 1000
1/2 = 0. We will terminate the algorithm, when number becomes 0.
So, decimal number = 1000+100+0+0 = 1100

Step by step implementation:


1. Take the number as input from the user.
2. Now, initialize binary number by 0, and place value by 1.
3. Run a while loop until the number is greater than 0.
4. In each iteration of this loop, find the remainder when divided by 2, multiply it by its
place value and then add it to the binary number.
5. After this, in each iteration, multiply the place value by 10 and divide the number by 2.

Pseudo Code for this problem:


Input = number
binary_number=0, pv=1
While number is greater than 0:
rem = number % 2
binary_number += rem* pv
pv *= 10;
number = number / 2
print(binary_number)

❏ Let us dry run the code:


number=12
● binary_number=0, pv=1

● rem=12%2=0
binary_number=0*1=0
pv=1*10=10
number=12/2=6.

● rem=6%2=0
binary_number=0+0*10=0
pv=10*10=100
number=6/2=3.

● rem=3%2=1
binary_number=0+1*100=100
pv=100*10=1000
number=3/2=1.

● rem=1%2=1
binary_number=100+1*1000=1100
pv=1000*10=10000
number=½=0

● As number is equal to 0, so print the binary number.


● Final output:
1100

You might also like