## CS 1401 Assignment #7

Date Assigned: Monday, October 15, or Tuesday, October 16, 2007.

Due Date: Monday, October 22, or Tuesday, October 23, 2007, before the beginning of your lab section.

Objective: The main objective of this assignment is to learn to design user-defined methods.

Programming assignment: to help convert decimal numbers to binary code,

• write a method that, given a positive integer, returns its binary code, and
• write a program that uses this method.
Test your program on an example of converting 15 and 22 (or, if your lab is on TR, 16 and 23).

Reminder: The following algorithm should be used to convert a decimal positive integer n into the binary form (as a string): you divide n by 2, keep a remainder. Divide the result by 2, keep a remainder, etc. until we get 0. The remainders, when read bottom to top, form the desired binary number.

Example of a binary code: for n = 13, we have

```13 / 2 = 6 rem 1
6 / 2 = 3 rem 0
3 / 2 = 1 rem 1
1 / 2 = 0 rem 1
```
When we read the remainders from bottom to top, we get 1101, which is exactly the binary representation of 13 -- since 1 * 8 + 1 * 4 + 0 * 2 + 1 * 1 = 8 + 4 + 1 = 13.

Hint: make a loop in which a string is gradually increased. Originally, the result-so-far is the input integer (e.g., 13), the string-so-far is empty. Within the loop, you divide the result-so-far by 2, compute the remainder, and add the corresponding one-character string ("0" or "1") to the left of the string-so-far, etc.

For extra credit: programming assignment 4 from p. 438 of the book.

```
Solution:

public String convert(input number){
int resultSoFar;
int remainder;
String stringSoFar = "";
String frontSymbol;

//initialization
resultSoFar = number;

//translating to binary
while (resultSoFar > 0){
//dividing by 2 and computing the remainder
remainder = resultSoFar % 2;
resultSoFar /= 2;

//adding a character to the string
if (remainder == 0)
{frontSymbol = "0";}
else
{frontSymbol = "1";}
stringSoFar = frontSymbol + stringSoFar;
}
return stringSoFar;
}

public static void main(String [] args){
System.out.println("The binary form of 15 is " +
convert(15));
System.out.println("The binary form of 22 is " +
convert(22));
}

Homework assignment: on a separate sheet of paper, solve Ex. 2,
4, and 8 at the end of Chapter 7 (on pp. 429 and 431).

Deliverables: as instructed by your TA.
```