## 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.

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.