13.2 M o r e Examples with Simple Variables | 641
statement—either anifor aswitch. A branching structure serves as the main control structure
in a recursive method; a looping structure is the main control structure in an iterative method.
Converting Decimal Integers to Binary Numbers
You enter integer data in decimal form, and the computer converts these decimal numbers
to binary form for use within a program. Do you know how decimal integers are converted
to binary numbers? The algorithm for this conversion follows:
1.Take the decimal number and divide it by 2.
2.Make the remainder the rightmost digit in the answer.
3.Replace the original dividend with the quotient.
4.Repeat, placing each new remainder to the left of the previous one.
5.Stop when the quotient is 0.
This algorithm is clearly meant for a calculator and paper and pencil. Certainly, we can-
not implement expressions such as “to the left of” in Java as yet. Let’s do an example—con-
vert 42 from base–10 to base–2—to get a feel for the algorithm before we try to write a
computer solution. Remember, the quotient in one step becomes the dividend in the next step.
The answer is the sequence of remainders from last to first. Therefore, the decimal num-
ber 42 is 101010 in binary.
Step 1
21
2 ) 42
4
2
2
0
Step 3
5
2 ) 10
10
0
Step 5
1
2 ) 2
2
0
← Quotient
← Remainder
← Quotient
← Remainder
← Quotient
← Remainder
Step 2
10
2 ) 21
22
1
0
1
Step 4
2
2 ) 5
4
1
Step 6
0
2 ) 1
0
1
← Quotient
← Remainder
← Quotient
← Remainder
← Quotient
← Remainder