CS 1401 Assignment #5

Date Assigned: Monday, September 25, or Tuesday, September 26, 2006.

Due Date: Monday, October 2, or Tuesday, October 3, 2006, before the beginning of your lab section.

Objective: The main objective of this assignment is to practice using loops.

Programming assignment: It is well known that computers use a binary system to represent integers. The following algorithm is used to convert a decimal positive integer n into the binary form: 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.

Write a program that, given an integer, uses the above algorithm to return a binary representation of this number (as a string).

Example: 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.

Hint: originally, the division-result is 13, the string-so-far is empty. Within the loop, you divide the division-result by 2, compute the remainder, and depending on whether the remainder is 0 or 1, add the corresponding one-character string '0' or '1' to the left of the string-so-far.

For extra credit: write a program that transforms binary back into decimal. Main idea:

Example: for the string 1101, Since the remaining string is empty, the value-so-far (13) is returned as the result.

Homework assignment: on a separate sheet of paper, solve Ex. 6, 10, 18, and 24 at the end of Chapter 5.

Deliverables: as instructed by your TA.