CS46A Introduction to Programming—Online Section

Spring 2014 | Cay S. Horstmann | Department of Computer Science | San Jose State University

# Week 8

1. Videos: Introduction Solutions to Homework 7a | 7b | 7c
2. Work through Udacity videos Lesson 6.1.
3. Read Sections 6.1 to 6.3 of the textbook.
4. Take the quizzes on Monday and Thursday.
5. Turn in the draft of Homework 8 on Wednesday and the final version on Sunday.
6. Work through Lab 7 and join a Webex session if you have a question and when you are ready show off your work.
7. Week 7 homework solutions are here.

## Homework

• Part A.

Modify the program from Section 6.1 of your textbook so that the user can supply the interest rate. For very small interest rates, it may take very long for the balance to double. Suppose the user can’t wait for more than twenty years. Stop adding interest when the balance has doubled or twenty years have elapsed.

For the draft, just read in the interest rate.

code-check for draft | final

• Part B. First, perform a walkthrough through the following loop:
```String s = "tooth";
String rest = s;
String result = "";
while (rest.length() > 1)
{
String first = rest.substring(0, 1);
rest = rest.substring(1);
if (rest.contains(first))
{
result = result + first;
}
}
System.out.println(result);
```
rest result first

As you can see, the loop eliminates duplicate letters. But with a string such as “Mississippi”, you will note that letters that occur three or more times are printed more than once. Modify the loop so that each repeated letter is printed exactly once.

Draft: Simply implement the loop as in the walkthrough.

code-check for draft | final

• Part C.

Looping through all pixels of a picture as in the Udacity videos in a single loop, darken the picture like this:

In the draft, just color the last pixel of each row black.

Hint: To recover the column position within a row, use `i % pic.getWidth()`. For example, suppose the picture is 100 pixels wide. Then as `i` goes from 0 ... 99 (first row) 100 ... 199 (second row) 200 ... 299 (third row), etc. then `i % pic.getWidth()` is 0 ... 99 0 ... 99 0 ... 99 etc. That should make the draft pretty easy.

For the final version, you need to multiply each color by a factor that is 1.0 at the left edge, and 0.0 at the right edge. You need to figure out how to transform 0 1 2 3 ... 98 99 into 1.0 f1 f2 ... f97 0.0, where each of these values are spaced evenly.

To see how to do that, imagine that there would only be five columns. Then you'd transform 0 1 2 3 4 into 1.0 f1 f2 f3 0.0 = 1.0 0.75 0.5 0.25 0.0. Now it's just algebra to get the i-th factor.

code-check for draft | final