CS 50 Homework 7 (Section 1 Prof. Marshall)
Due by class time Tuesday, March 12
- Study the code for the recursive arithmetic definitions discussed in
class. You can find the code in the class folder under
Lectures/week07/Arithmetic. The file Decimal/Arithmetic.java
represents numbers as strings of decimal digits (base 10), while
Binary/Arithmetic.java uses a binary representation (base 2).
(See pages 63-64 of your textbook for more details on binary numbers.)
Compile and run this code to get a feel for what it does.
Suppose we
want to add methods to Binary/Arithmetic.java to convert between
ordinary int's and binary strings. The following two (incomplete)
method definitions are all we need. Your job is to fill in the missing
blanks. Remember to think recursively! Hint: each of the missing pieces
will easily fit on a single line. Feel free to test out your answer on the
computer to see if it works.
// converts an ordinary integer to its binary string representation
public static String toBinary(int a) {
if (...???...) {
return ...???...
} else {
return ...???...
}
}
// converts a binary string back to an ordinary integer
public static int toInteger(String a) {
if (...???...) {
return ...???...
} else {
return ...???...
}
}
Files to submit: NONE. For this problem, you don't need to submit
code, just write out your completed definitions on a piece of paper and
hand this in during class.
- Use a recursive method to solve the LongestWord problem from Lab 5. Using
a StringTokenizer, read in a sentence from the user and print out the
longest word in the sentence. Files to submit: LongestWordRec.java
- As in Lab 4, write an applet that draws a bulls-eye of concentric circles
in alternating red and white colors. Fill the largest possible square region of
the applet window. Use a recursive method to draw the bulls-eye. Hint:
pass the corner coordinates and diameter of the bullseye as parameters to
your method. What other parameter(s) do you need to draw the bullseye?
Files to submit: BullseyeRec.java, BullseyeRec.html
- As in Lab 6, write an applet that draws a pyramid of bricks. Draw the
pyramid recursively. You should ask the user for the number of levels in the
pyramid, and the width and height of the bricks. Files to submit:
PyramidRec.java, PyramidRec.html
- Programming Exercise 7.15 (page 310). Prompt the user for two
strings, then use your find method to see if the first string is a
substring of the second. Files to submit: FindString.java
- Programming Exercise 7.14 (page 310). Files to submit:
Towers.java
Turning in Your Homework
To turn in your homework, put the specified files into a single folder
named Your Name HW 7 and drop this folder into the drop box.
If needed, you may copy your folder to a CLEAN floppy disk (one containing no
other files or folders), and hand this in at the beginning of class, instead of
using the drop box.