Codementor Events

Java

Published Sep 22, 2018

Normal numbers are made of the digits 0 through 9. There are ten possible digits
so we call this decimal. Big numbers use more than one digit, for example 427.
Binary numbers are made of just zeroes (0) and ones (1). Numbers bigger than 1
use more than one binary digit, for example, the number 5 is 101 in binary. The
number 13 is 1101 in binary. This is how a computer can store any number even
though its circuits hold just ones and zeroes.
Write a program that converts small decimal numbers in the range 0 – 15 to
binary numbers. The user should enter (type in) the number to convert. You can
convert decimal numbers to binary using fairly simple math (see “Hint” below).
Here’s what an example run of the program might look like:
Please enter a number from 0 to 15:
13
Here is your number converted to binary (read from bottom to top)
1
0
1
1
Reading the zeros and ones from bottom to top gives the answer (1101). You can
assume the user always enters a number from 0 to 15 (no input checking is
necessary).
Hint: Here’s one way to do it, but there are other ways:
a) Calculate the remainder when the number is divided by 2. This is the first
binary digit, print it out. For example the remainder when 13 is divided by 2
is 1. You can use the % operator to calculate remainders.
b) Divide the number by 2 and throw away the remainder, this is your new
number. For example, starting with 13 the new number is 6.
c) Do steps (a) and (b) above three more times. Each time step (a) should
start with the “new” number from the last step (b).
Note: Do not use ‘if’ since we haven’t learned this yet. If you know how to use a
‘for’ loop then you may do so, but I suggest you don’t since we haven’t learned
loops.

Discover and read more posts from Ishmael spence
get started