Loops Notes
Loops Notes
Loops
Chapter Goals
Chapter Contents
4.1 The while Loop 140 Special Topic 4.2: Redirection of Input
Syntax 4.1: while Statement 141 and Output 161
Common Error 4.1: Don’t Think “Are We Video Example 4.1: Evaluating a Cell
There Yet?” 144 Phone Plan
Common Error 4.2: Infinite Loops 145 4.6 Problem Solving:
Common Error 4.3: Off-by-One Errors 145 Storyboards 162
Random Fact 4.1: The First Bug 146
4.7 Common Loop Algorithms 165
4.2 Problem Solving: How To 4.1: Writing a Loop 169
Hand-Tracing 147
Worked Example 4.1: Credit Card Processing
4.3 The for Loop 150 4.8 Nested Loops 172
Syntax 4.2: for Statement 152 Worked Example 4.2: Manipulating the Pixels
Programming Tip 4.1: Use for Loops for Their in an Image
Intended Purpose Only 155
4.9 Application: Random Numbers
Programming Tip 4.2: Choose Loop Bounds That
and Simulations 176
Match Your Task 155
Programming Tip 4.3: Count Iterations 156 Special Topic 4.3: Drawing Graphical Shapes 179
Video Example 4.2: Drawing a Spiral
4.4 The do Loop 156 Random Fact 4.2: Software Piracy 182
Programming Tip 4.4: Flowcharts for Loops 157
4.5 Application: Processing
Sentinel Values 158
Special Topic 4.1: The Loop-and-a-Half Problem
and the break Statement 160
139
In a loop, a part of a program is repeated over and over,
until a specific goal is reached. Loops are important for
calculations that require repeated steps and for processing
input consisting of many data items. In this chapter, you will
learn about loop statements in Java, as well as techniques
for writing programs that process input and simulate
activities in the real world.
Start with a year value of 0, a column for the interest, and a balance of $10,000.
Repeat the following steps while the balance is less than $20,000.
Add 1 to the year value.
Compute the interest as balance x 0.05 (i.e., 5 percent interest).
Add the interest to the balance.
Report the final year value as the answer.
You now know how to declare and update the variables in Java. What you don’t yet
know is how to carry out “Repeat steps while the balance is less than $20,000”.
140
4.1 The while Loop 141
A loop executes
In Java, the while statement implements such a True
instructions repetition (see Syntax 4.1). It has the form
repeatedly while a
while (condition) Increment
condition is true.
{ year
statements
}
A while statement is an example of a loop. If you draw a flowchart, the flow of execu
tion loops again to the point where the condition is tested (see Figure 1).
When you declare a variable inside the loop body, the variable is created for each
iteration of the loop and removed after the end of each iteration. For example, con
sider the interest variable in this loop:
while (balance < TARGET)
{ A new interest variable
year++; is created in each iteration.
double interest = balance * RATE / 100;
balance = balance + interest;
} // interest no longer declared here
In contrast, the balance and years variables were declared outside the loop body. That
way, the same variable is used for all iterations of the loop.
Here is the program that solves the investment problem. Figure 2 illustrates the pro
gram’s execution.
section_1/DoubleInvestment.java
1 /**
2 This program computes the time required to double an investment.
3 */
4 public class DoubleInvestment
5 {
6 public static void main(String[] args)
7 {
8 final double RATE = 5;
9 final double INITIAL_BALANCE = 10000;
10 final double TARGET = 2 * INITIAL_BALANCE;
11
12 double balance = INITIAL_BALANCE;
13 int year = 0;
14
15 // Count the years required for the investment to double
16
17 while (balance < TARGET)
18 {
19 year++;
20 double interest = balance * RATE / 100;
21 balance = balance + interest;
22 }
23
24 System.out.println("The investment doubled after "
25 + year + " years.");
26 }
27 }
Program Run
The investment doubled after 15 years.
S e l f C h e c k 1. How many years does it take for the investment to triple? Modify the program
and run it.
2. If the interest rate is 10 percent per year, how many years does it take for the
investment to double? Modify the program and run it.
3. Modify the program so that the balance after each year is printed. How did you
do that?
4. Suppose we change the program so that the condition of the while loop is
while (balance <= TARGET)
What is the effect on the program? Why?
5. What does the following loop print?
int n = 1;
while (n < 100)
{
n = 2 * n;
System.out.print(n + " ");
}
Practice It Now you can try these exercises at the end of the chapter: R4.1, R4.5, P4.14.
144 Chapter 4 Loops
i = 0; sum = 0; (No output) The statement sum < 0 is false when the
while (sum < 0) condition is first checked, and the loop
{ is never executed.
i++; sum = sum - i;
Print i and sum;
}
Some people try to solve off-by-one errors by randomly inserting +1 or -1 until the pro
gram seems to work—a terrible strategy. It can take a long time to compile and test all the vari
ous possibilities. Expending a small amount of mental effort is a real time saver.
Fortunately, off-by-one errors are easy to avoid, simply by
thinking through a couple of test cases and using the information
An off-by-one error is
from the test cases to come up with a rationale for your decisions. a common error
Should year start at 0 or at 1? Look at a scenario with simple val when programming
ues: an initial balance of $100 and an interest rate of 50 percent. After loops. Think through
year 1, the balance is $150, and after year 2 it is $225, or over $200. So simple test cases
to avoid this type
the investment doubled after 2 years. The loop executed two times, of error.
incrementing year each time. Hence year must start at 0, not at 1.
year balance
0 $100
1 $150
2 $225
In other words, the balance variable denotes the balance after the end of the year. At the outset,
the balance variable contains the balance after year 0 and not after year 1.
Next, should you use a < or <= comparison in the test? This is harder to figure out, because
it is rare for the balance to be exactly twice the initial balance. There is one case when this
happens, namely when the interest is 100 percent. The loop executes once. Now year is 1, and
balance is exactly equal to 2 * INITIAL_BALANCE. Has the investment doubled after one year? It
has. Therefore, the loop should not execute again. If the test condition is balance < TARGET, the
loop stops, as it should. If the test condition had been balance <= TARGET, the loop would have
executed once more.
In other words, you keep adding interest while the balance has not yet doubled.
n sum digit
The first two variables are initialized with 1729 and 0 before the loop is entered.
int n = 1729;
int sum = 0; n sum digit
while (n > 0) 1729 0
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);
Because n is greater than zero, enter the loop. The variable digit is set to 9 (the remain
der of dividing 1729 by 10). The variable sum is set to 0 + 9 = 9.
int n = 1729;
int sum = 0; n sum digit
while (n > 0) 1729 0
{
int digit = n % 10; 9 9
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);
148 Chapter 4 Loops
Finally, n becomes 172. (Recall that the remainder in the division 1729 / 10 is dis
carded because both arguments are integers.)
Cross out the old values and write the new ones under the old ones.
int n = 1729;
int sum = 0; n sum digit
while (n > 0) 1729 0
{
int digit = n % 10; 172 9 9
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);
int n = 1729;
int sum = 0;
while (n > 0)
{
Because n equals zero,
int digit = n % 10; this condition is not true.
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);
The condition n > 0 is now false. Continue with the statement after the loop.
int n = 1729;
int sum = 0; n sum digit output
while (n > 0) 1729 0
{
int digit = n % 10; 172 9 9
sum = sum + digit; 17 11 2
n = n / 10;
1 18 7
}
System.out.println(sum); 0 19 1 19
This statement is an output statement. The value that is output is the value of sum,
which is 19.
Of course, you can get the same answer by just running the code. However, hand-
A N I M AT I O N
tracing can give you an insight that you would not get if you simply ran the code.
Tracing a Loop Consider again what happens in each iteration:
• We extract the last digit of n.
• We add that digit to sum.
• We strip the digit off n.
Hand-tracing can
In other words, the loop forms the sum of the digits in n. You now know what the
help you understand loop does for any value of n, not just the one in the example. (Why would anyone
how an unfamiliar want to form the sum of the digits? Operations of this kind are useful for checking
algorithm works.
the validity of credit card numbers and other forms of ID numbers—see Exercise
P4.32.)
Hand-tracing can
Hand-tracing does not just help you understand code that works correctly. It is
show errors in code a powerful technique for finding errors in your code. When a program behaves in a
or pseudocode. way that you don’t expect, get out a sheet of paper and track the values of the vari
ables as you mentally step through the code.
You don’t need a working program to do hand-tracing. You can hand-trace
pseudocode. In fact, it is an excellent idea to hand-trace your pseudocode before you
go to the trouble of translating it into actual code, to confirm that it works correctly.
S e l f C h e c k 6. Hand-trace the following code, showing the value of n and the output.
int n = 5;
while (n >= 0)
{
n--;
System.out.print(n);
}
150 Chapter 4 Loops
7. Hand-trace the following code, showing the value of n and the output. What
potential error do you notice?
int n = 1;
while (n <= 3)
{
System.out.print(n + ", ");
n++;
}
8. Hand-trace the following code, assuming that a is 2 and n is 4. Then explain what
the code does for arbitrary values of a and n.
int r = 1;
int i = 1;
while (i <= n)
{
r = r * a;
i++;
}
9. Trace the following code. What error do you observe?
int n = 1;
while (n != 50)
{
System.out.println(n);
n = n + 10;
}
10. The following pseudocode is intended to count the number of digits in the
number n:
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
Trace the pseudocode for n = 123 and n = 100. What error do you find?
Practice It Now you can try these exercises at the end of the chapter: R4.3, R4.6.
Because this loop type is so common, there is a special form for it, called the for loop
(see Syntax 4.2).
4.3 The for Loop 151
A N I M AT I O N
executed together (see Figure 3).
The for Loop • The initialization is executed once, before the loop is entered. 1
• The condition is checked before each iteration. 2 5
• The update is executed after each iteration. 4
1 Initialize counter
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }
2 Check condition
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }
4 Update counter
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 2 }
for (i = 0; i <= 5; i++) 012345 Note that the loop is executed 6 times. (See
Programming Tip 4.3 on page 156.)
for (i = 5; i >= 0; i--) 543210 Use i-- for decreasing values.
Such a variable is declared for all iterations of the loop, but you cannot use it after the
loop. If you declare the counter variable before the loop, you can continue to use it
after the loop:
int counter;
for (counter = 1; counter <= 10; counter++)
{
. . .
}
// counter still declared here
Here is a typical use of the for loop. We want to print the balance of our savings
account over a period of years, as shown in this table:
Year Balance
1 10500.00
year = 1
2 11025.00
3 11576.25
4 12155.06
5 12762.82 False
year ≤ nyears ?
section_3/InvestmentTable.java
1 import java.util.Scanner;
2
3 /**
4 This program prints a table showing the growth of an investment.
5 */
6 public class InvestmentTable
7 {
8 public static void main(String[] args)
9 {
10 final double RATE = 5;
11 final double INITIAL_BALANCE = 10000;
154 Chapter 4 Loops
Program Run
Enter number of years: 10
1 10500.00
2 11025.00
3 11576.25
4 12155.06
5 12762.82
6 13400.96
7 14071.00
8 14774.55
9 15513.28
10 16288.95
Another common use of the for loop is to traverse all characters of a string:
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
Process ch
}
Note that the counter variable i starts at 0, and the loop is terminated when i reaches
the length of the string. For example, if str has length 5, i takes on the values 0, 1, 2, 3,
and 4. These are the valid positions in the string.
S e l f C h e c k 11. Write the for loop of the InvestmentTable.java program as a while loop.
12. How many numbers does this loop print?
for (int n = 10; n >= 0; n--)
{
System.out.println(n);
}
13. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
14. Write a for loop that computes the sum of the integers from 1 to n.
15. How would you modify the for loop of the InvestmentTable.java program to
print all balances until the investment has doubled?
Practice It Now you can try these exercises at the end of the chapter: R4.4, R4.10, P4.8, P4.13.
4.3 The for Loop 155
Programming Tip 4.1 Use for Loops for Their Intended Purpose Only
A for loop is an idiom for a loop of a particular form. A value runs from the start to the end,
with a constant increment or decrement.
The compiler won’t check whether the initialization, condition, and update expressions are
related. For example, the following loop is legal:
// Confusing—unrelated expressions
for (System.out.print("Inputs: "); in.hasNextDouble(); sum = sum + x)
{
x = in.nextDouble();
}
However, programmers reading such a for loop will be confused because it does not match
their expectations. Use a while loop for iterations that do not follow the for idiom.
You should also be careful not to update the loop counter in the body of a for loop. Con
sider the following example:
for (int counter = 1; counter <= 100; counter++)
{
if (counter % 10 == 0) // Skip values that are divisible by 10
{
counter++; // Bad style—you should not update the counter in a for loop
}
System.out.println(counter);
}
Updating the counter inside a for loop is confusing because the counter is updated again at the
end of the loop iteration. In some loop iterations, counter is incremented once, in others twice.
This goes against the intuition of a programmer who sees a for loop.
If you find yourself in this situation, you can either change from a for loop to a while loop,
or implement the “skipping” behavior in another way. For example:
for (int counter = 1; counter <= 100; counter++)
{
if (counter % 10 != 0) // Skip values that are divisible by 10
{
System.out.println(counter);
}
}
Programming Tip 4.2 Choose Loop Bounds That Match Your Task
Suppose you want to print line numbers that go from 1 to 10. Of course, you will use a loop:
for (int i = 1; i <= 10; i++)
The values for i are bounded by the relation 1 ≤ i≤ 10. Because there are ≤ on both bounds, the
bounds are called symmetric.
When traversing the characters in a string, it is more natural to use the bounds
for (int i = 0; i < str.length(); i++)
In this loop, i traverses all valid positions in the string. You can access the ith character as str.
charAt(i). The values for i are bounded by 0 ≤ i < str.length(), with a ≤ to the left and a < to the
right. That is appropriate, because str.length() is not a valid position. Such bounds are called
asymmetric.
In this case, it is not a good idea to use symmetric bounds:
for (int i = 0; i <= str.length() - 1; i++) // Use < instead
The asymmetric form is easier to understand.
156 Chapter 4 Loops
The body of the do loop is executed first, then the condition is tested.
Some people call such a loop a post-test loop because the condition is tested after
completing the loop body. In contrast, while and for loops are pre-test loops. In those
ONLINE E x a m p l e loop types, the condition is tested before entering the loop body.
A program to A typical example for a do loop is input validation. Suppose you ask a user to enter
illustrate the use of a value < 100. If the user doesn’t pay attention and enters a larger value, you ask
the do loop for input
validation.
again, until the value is correct. Of course, you cannot test the value until the user has
entered it. This is a perfect fit for the do loop (see Figure 5):
4.4 The do Loop 157
int value;
do Prompt user
{ to enter
System.out.print("Enter an integer < 100: "); a value < 100
value = in.nextInt();
}
while (value >= 100);
Copy the input
to value
S e l f C h e c k 16. Suppose that we want to check for inputs that are
at least 0 and at most 100. Modify the do loop for
this check.
17. Rewrite the input check do loop using a while loop.
What is the disadvantage of your solution? True
value ≥ 100?
18. Suppose Java didn’t have a do loop. Could you
rewrite any do loop as a while loop?
19. Write a do loop that reads integers and computes False
their sum. Stop when reading the value 0.
20. Write a do loop that reads integers and computes their sum. Stop when reading a
zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then
the sum is 14 and the loop stops.
Practice It Now you can try these exercises at the end of the chapter: R4.9, R4.16, R4.17.
False
Condition? Loop body
True
False
As described in Section 3.5, you want to avoid “spaghetti code” in your flowcharts. For loops,
that means that you never want to have an arrow that points inside a loop body.
158 Chapter 4 Loops
There is just one problem: When the loop is entered for the first time, no data value
has been read. We must make sure to initialize salary with some value other than the
sentinel:
double salary = 0;
// Any value other than –1 will do
After the loop has finished, we compute and print the average. Here is the complete
program:
section_5/SentinelDemo.java
1 import java.util.Scanner;
2
3 /**
4 This program prints the average of salary values that are terminated with a sentinel.
5 */
4.5 Application: Processing Sentinel Values 159
Program Run
Enter salaries, -1 to finish: 10 10 40 -1
Average salary: 20
Special Topic 4.1 on page 160 shows an alternative mechanism for leaving such a loop.
160 Chapter 4 Loops
Now consider the case in which any number (positive, negative, or zero) can be
an acceptable input. In such a situation, you must use a sentinel that is not a number
(such as the letter Q). As you have seen in Section 3.8, the condition
in.hasNextDouble()
is false if the next input is not a floating-point number. Therefore, you can read and
process a set of inputs with the following loop:
System.out.print("Enter values, Q to quit: ");
while (in.hasNextDouble())
{
value = in.nextDouble();
Process value.
}
S e l f C h e c k 21. What does the SentinelDemo.java program print when the user immediately types
–1 when prompted for a value?
22. Why does the SentinelDemo.java program have two checks of the form
salary != -1
23. What would happen if the declaration of the salary variable in SentinelDemo.java
was changed to
double salary = -1;
24. In the last example of this section, we prompt the user “Enter values, Q to quit.”
What happens when the user enters a different letter?
25. What is wrong with the following loop for reading a sequence of values?
System.out.print("Enter values, Q to quit: ");
do
{
double value = in.nextDouble();
sum = sum + value;
count++;
}
while (in.hasNextDouble());
Practice It Now you can try these exercises at the end of the chapter: R4.13, P4.27, P4.28.
Special Topic 4.1 The Loop-and-a-Half Problem and the break Statement
Consider again this loop for processing inputs until a sentinel value has been reached:
boolean done = false;
while (!done)
{
double value = in.nextDouble();
if (value == -1)
{
done = true;
}
else
{
Process value.
}
}
4.5 Application: Processing Sentinel Values 161
The actual test for loop termination is in the middle of the loop, not at the top. This is called a
loop and a half because one must go halfway into the loop before knowing whether one needs
to terminate.
As an alternative, you can use the break reserved word.
while (true)
{
double value = in.nextDouble();
if (value == -1) { break; }
Process value.
}
The break statement breaks out of the enclosing loop, independent of the loop condition.
When the break statement is encountered, the loop is terminated, and the statement following
the loop is executed.
In the loop-and-a-half case, break statements can be beneficial. But it is difficult to lay down
clear rules as to when they are safe and when they should be avoided. We do not use the break
statement in this book.
Figure 6
Storyboard for the
Design of a Web
Application
4.6 Problem Solving: Storyboards 163
Let’s get started with a storyboard panel. It is a good idea to write the user inputs in
a different color. (Underline them if you don’t have a color pen handy.)
The storyboard shows how we deal with a potential confusion. A user who wants to
know how many inches are 30 centimeters may not read the first prompt carefully
and specify inches. But then the output is “30 in = 76.2 cm”, alerting the user to the
problem.
The storyboard also raises an issue. How is the user supposed to know that “cm”
and “in” are valid units? Would “centimeter” and “inches” also work? What happens
when the user enters a wrong unit? Let’s make another storyboard to demonstrate
error handling.
To eliminate frustration, it is better to list the units that the user can supply.
From unit (in, ft, mi, mm, cm, m, km, oz, lb, g, kg, tsp, tbsp, pint, gal): cm
To unit: in
No need to list the units again
We switched to a shorter prompt to make room for all the unit names. Exercise R4.21
explores a different alternative.
There is another issue that we haven’t addressed yet. How does the user quit the
program? The first storyboard suggests that the program will go on forever.
We can ask the user after seeing the sentinel that terminates an input sequence.
164 Chapter 4 Loops
As you can see from this case study, a storyboard is essential for developing a work
ing program. You need to know the flow of the user interaction in order to structure
your program.
S e l f C h e c k 26. Provide a storyboard panel for a program that reads a number of test scores and
prints the average score. The program only needs to process one set of scores.
Don’t worry about error handling.
27. Google has a simple interface for converting units. You just type the question,
and you get the answer.
30. Produce a storyboard for a program that compares the growth of a $10,000
investment for a given number of years under two interest rates.
Practice It Now you can try these exercises at the end of the chapter: R4.21, R4.22, R4.23.
4.7 Common Loop Algorithms 165
To compute an
Computing the sum of a number of inputs is a very common task. Keep a running
average, keep a total, a variable to which you add each input value. Of course, the total should be
total and a count initialized with 0.
of all values.
double total = 0;
while (in.hasNextDouble())
{
double input = in.nextDouble();
total = total + input;
}
Note that the total variable is declared outside the loop. We want the loop to update
a single variable. The input variable is declared inside the loop. A separate variable is
created for each input and removed at the end of each loop iteration.
To compute an average, count how many values you have, and divide by the count.
Be sure to check that the count is not zero.
double total = 0;
int count = 0;
while (in.hasNextDouble())
{
double input = in.nextDouble();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
For example, if str is "My Fair Lady", spaces is incremented twice (when i is 2 and 7).
166 Chapter 4 Loops
Note that the spaces variable is declared outside the loop. We want the loop to
update a single variable. The ch variable is declared inside the loop. A separate variable
is created for each iteration and removed at the end of each loop iteration.
This loop can also be used for scanning inputs. The following loop reads text, a
word at a time, and counts the number of words with at most three letters:
int shortWords = 0;
while (in.hasNext())
{
String input = in.next();
if (input.length() <= 3)
{
shortWords++;
}
}
Note that the variable input is declared outside the while loop because you will want to
use the input after the loop has finished.
To compare adjacent
When processing a sequence of values in a loop, you sometimes need to compare a
inputs, store the value with the value that just preceded it. For example, suppose you want to check
preceding input in whether a sequence of inputs contains adjacent duplicates such as 1 7 2 9 9 4 9.
a variable.
Now you face a challenge. Consider the typical loop for reading a value:
double input;
while (in.hasNextDouble())
{
input = in.nextDouble();
. . .
}
One problem remains. When the loop is entered for the first time, input has not yet
been read. You can solve this problem with an initial input operation outside the loop:
double input = in.nextDouble();
while (in.hasNextDouble())
O n l i n e E x a m p l e {
A program using double previous = input;
common loop input = in.nextDouble();
algorithms. if (input == previous)
{
System.out.println("Duplicate input");
}
}
S e l f C h e c k 31. What total is computed when no user input is provided in the algorithm in
Section 4.7.1?
32. How do you compute the total of all positive inputs?
33. What are the values of position and ch when no match is found in the algorithm
in Section 4.7.3?
34. What is wrong with the following loop for finding the position of the first space
in a string?
boolean found = false;
for (int position = 0; !found && position < str.length(); position++)
{
4.7 Common Loop Algorithms 169
char ch = str.charAt(position);
if (ch == ' ') { found = true; }
}
35. How do you find the position of the last space in a string?
36. What happens with the algorithm in Section 4.7.5 when no input is provided at
all? How can you overcome that problem?
Practice It Now you can try these exercises at the end of the chapter: P4.5, P4.9, P4.10.
Similarly, we must find a general way of setting the highest month. We need a variable that
stores the current month, running from 1 to 12. Then we can formulate the second loop action:
If value is higher than the highest temperature, set highest temperature to that value,
highest month to current month.
Altogether our loop is
Repeat
Read next value.
If value is higher than the highest temperature,
set highest temperature to that value,
set highest month to current month.
Increment current month.
Step 2 Specify the loop condition.
What goal do you want to reach in your loop? Typical examples are
• Has a counter reached its final value?
• Have you read the last input value?
• Has a value reached a given threshold?
In our example, we simply want the current month to reach 12.
Step 3 Determine the loop type.
We distinguish between two major loop types. A count-controlled loop is executed a defi
nite number of times. In an event-controlled loop, the number of iterations is not known in
advance—the loop is executed until some event happens.
Count-controlled loops can be implemented as for statements. For other loops, consider
the loop condition. Do you need to complete one iteration of the loop body before you can
tell when to terminate the loop? In that case, choose a do loop. Otherwise, use a while loop.
Sometimes, the condition for terminating a loop changes in the middle of the loop body. In
that case, you can use a Boolean variable that specifies when you are ready to leave the loop.
Follow this pattern:
boolean done = false;
while (!done)
{
Do some work.
If all work has been completed
{
done = true;
}
else
{
Do more work.
}
}
Such a variable is called a flag.
In summary,
• If you know in advance how many times a loop is repeated, use a for loop.
• If the loop body must be executed at least once, use a do loop.
• Otherwise, use a while loop.
In our example, we read 12 temperature values. Therefore, we choose a for loop.
Step 4 Set up variables for entering the loop for the first time.
List all variables that are used and updated in the loop, and determine how to initialize them.
Commonly, counters are initialized with 0 or 1, totals with 0.
4.7 Common Loop Algorithms 171
The trace demonstrates that highest month and highest value are properly set.
Step 7 Implement the loop in Java.
Here’s the loop for our example. Exercise P4.4 asks you to complete the program.
double highestValue;
highestValue = in.nextDouble();
int highestMonth = 1;
172 Chapter 4 Loops
x=1
True
n=1
False n≤4?
True
Print xn
n++
x++
Figure 7
Flowchart of a Nested Loop
There are 10 rows in the outer loop. For each x, the program prints four columns
in the inner loop (see Figure 7). Thus, a total of 10 × 4 = 40 values are printed.
Following is the complete program. Note that we also use loops to print the table
header. However, those loops are not nested.
section_8/PowerTable.java
1 /**
2 This program prints a table of powers of x.
3 */
4 public class PowerTable
5 {
6 public static void main(String[] args)
7 {
8 final int NMAX = 4;
9 final double XMAX = 10;
10
11 // Print table header
12
13 for (int n = 1; n <= NMAX; n++)
14 {
15 System.out.printf("%10d", n);
16 }
17 System.out.println();
174 Chapter 4 Loops
Program Run
1 2 3 4
x x x x
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561
10 100 1000 10000
S e l f C h e c k 37. Why is there a statement System.out.println(); in the outer loop but not in the
inner loop?
38. How would you change the program to display all powers from x0 to x5?
39. If you make the change in Self Check 38, how many values are displayed?
40. What do the following nested loops display?
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
System.out.print(i + j);
}
System.out.println();
}
41. Write nested loops that make the following pattern of brackets:
[][][][]
[][][][]
[][][][]
4.8 Nested Loops 175
Practice It Now you can try these exercises at the end of the chapter: R4.27, P4.19, P4.21.
section_9_1/RandomDemo.java
1 /**
2 This program prints ten random numbers between 0 and 1.
3 */
4 public class RandomDemo
5 {
6 public static void main(String[] args)
7 {
8 for (int i = 1; i <= 10; i++)
9 {
10 double r = Math.random();
11 System.out.println(r);
12 }
13 }
14 }
Program Run
0.6513550469421886
0.920193662882893
0.6904776061289993
0.8862828776788884
0.7730177555323139
0.3020238718668635
0.0028504531690907164
0.9099983981705169
0.1151636530517488
0.1592258808929058
4.9 Application: Random Numbers and Simulations 177
Actually, the numbers are not completely random. They are drawn from sequences
of numbers that don’t repeat for a long time. These sequences are actually computed
from fairly simple formulas; they just behave like random numbers (see Exercise
P4.25). For that reason, they are often called pseudorandom numbers.
to obtain a random integer between 0 and b - a, then add a, yielding a random value
between a and b:
int r = (int) (Math.random() * (b - a + 1)) + a;
section_9_2/Dice.java
1 /**
2 This program simulates tosses of a pair of dice.
3 */
4 public class Dice
5 {
6 public static void main(String[] args)
7 {
8 for (int i = 1; i <= 10; i++)
9 {
10 // Generate two random numbers between 1 and 6
11
12 int d1 = (int) (Math.random() * 6) + 1;
13 int d2 = (int) (Math.random() * 6) + 1;
14 System.out.println(d1 + " " + d2);
15 }
16 System.out.println();
17 }
18 }
Program Run
5 1
2 1
1 2
5 1
1 2
6 4
4 4
6 1
6 3
5 2
178 Chapter 4 Loops
section_9_3/MonteCarlo.java
1 /**
2 This program computes an estimate of pi by simulating dart throws onto a square.
3 */
4 public class MonteCarlo
5 {
6 public static void main(String[] args)
7 {
8 final int TRIES = 10000;
9
10 int hits = 0;
11 for (int i = 1; i <= TRIES; i++)
12 {
13 // Generate two random numbers between -1 and 1
14
15 double r = Math.random();
16 double x = -1 + 2 * r; // Between -1 and 1
17 r = Math.random();
18 double y = -1 + 2 * r;
19
4.9 Application: Random Numbers and Simulations 179
Program Run
Estimate for pi: 3.1504
S e l f C h e c k 42. How do you simulate a coin toss with the Math.random() method?
43. How do you simulate the picking of a random playing card?
44. Why does the loop body in Dice.java call Math.random() twice?
45. In many games, you throw a pair of dice to get a value between 2 and 12. What is
wrong with this simulated throw of a pair of dice?
int sum = (int) (Math.random() * 11) + 2;
46. How do you generate a random floating-point number ≥ 0 and < 100?
Practice It Now you can try these exercises at the end of the chapter: R4.28, P4.7, P4.24.
The draw method receives an object of type Graphics. The Graphics object has methods for
drawing shapes. It also remembers the color that is used for drawing operations. You can think
of the Graphics object as the equivalent of System.out for drawing shapes instead of printing
values.
Table 4 shows useful methods of the Graphics class.
g.drawLine(x1, y1, x2, y2) (x1, y1) and (x2, y2) are
the endpoints.
Basepoint Baseline
The program below draws the squares shown in Figure 8. When you want to produce your
own drawings, make a copy of this program and modify it. Replace the drawing tasks in the
draw method. Rename the class (for example, Spiral instead of TwoRowsOfSquares).
special_topic_3/TwoRowsOfSquares.java
1 import java.awt.Color;
2 import java.awt.Graphics;
3 import javax.swing.JFrame;
4 import javax.swing.JComponent;
5
6 /**
7 This program draws two rows of squares.
8 */
9 public class TwoRowsOfSquares
10 {
4.9 Application: Random Numbers and Simulations 181
.
Random Fact 4.2 Software Piracy
As you read this, you that they have an ample cheap supply honest and get by with a more afford
will have written a few of foreign software, but no local man able product?
computer programs and experienced ufacturers willing to design good soft Of course, piracy
firsthand how much effort it takes to ware for their own citizens, such as is not limited to
write even the humblest of programs. word processors in the local script or software. The same
Writing a real software product, such financial programs adapted to the local issues arise for other
as a financial application or a computer tax laws. digital products as
game, takes a lot of time and money. When a mass market for software well. You may have
Few people, and fewer companies, are first appeared, vendors were enraged had the opportunity
going to spend that kind of time and by the money they lost through piracy. to obtain copies of
money if they don’t have a reasonable They tried to fight back by various songs or movies
chance to make more money from their schemes to ensure that only the legiti- without payment. Or you may have
effort. (Actually, some companies give mate owner could use the software, been frustrated by a copy protec-
away their software in the hope that such as dongles—devices that must tion device on your music player that
users will upgrade to more elaborate be attached to a printer port before made it diffi cult for you to listen to
paid versions. Other companies give the software will run. Legitimate users songs that you paid for. Admittedly,
away the software that enables users to hated these measures. They paid for it can be diffi cult to have a lot of sym-
read and use files but sell the software the software, but they had to suffer pathy for a musical ensemble whose
needed to create those files. Finally, through inconveniences, such as hav- publisher charges a lot of money for
there are individuals who donate their ing multiple dongles stick out from what seems to have been very little
time, out of enthusiasm, and produce their computer. In the United States, effort on their part, at least when
programs that you can copy freely.) market pressures forced most vendors compared to the effort that goes into
When selling software, a company to give up on these copy protection designing and implementing a soft-
must rely on the honesty of its cus schemes, but they are still common- ware package. Nevertheless, it seems
tomers. It is an easy matter for an place in other parts of the world. only fair that artists and authors
unscrupulous person to make copies Because it is so easy and inexpen receive some compensation for their
of computer programs without paying sive to pirate software, and the chance efforts. How to pay artists, authors,
for them. In most countries that is ille of being found out is minimal, you and programmers fairly, without
gal. Most governments provide legal have to make a moral choice for your burdening honest customers, is an
protection, such as copyright laws and self. If a package that you would really unsolved problem at the time of this
patents, to encourage the develop like to have is too expensive for your writing, and many computer scientists
ment of new products. Countries that budget, do you steal it, or do you stay are engaged in research in this area.
tolerate widespread piracy have found
C h a p t e r Summ a r y
• The for loop is used when a value runs from a starting point to an ending point
with a constant increment or decrement.
• The do loop is appropriate when the loop body must be executed at least once.
• A sentinel value denotes the end of a data set, but it is not part of
the data.
• You can use a Boolean variable to control a loop. Set the variable
to true before entering the loop, then set it to false to leave the
loop.
• Use input redirection to read input from a file. Use output
redirection to capture program output in a file.
• When the body of a loop contains another loop, the loops are nested. A typical
use of nested loops is printing a table with rows and columns.
S ta n d a r d L ib r a r y I t e m s I n t r o duc e d i n t h i s C h a p t e r
java.awt.Color java.lang.Math
java.awt.Graphics random
drawLine
drawOval
drawRect
drawString
setColor
R e vi e w E x e r ci s e s
• R4.5 What is an infinite loop? On your computer, how can you terminate a program that
executes an infinite loop?
• R4.6 Write a program trace for the pseudocode in Exercise P4.6, assuming the input val
ues are 4 7 –2 –5 0.
Review Exercises 185
•• R4.7 What is an “off-by-one” error? Give an example from your own programming
experience.
• R4.8 What is a sentinel value? Give a simple rule when it is appropriate to use a numeric
sentinel value.
• R4.9 Which loop statements does Java support? Give simple rules for when to use each
loop type.
• R4.10 How many iterations do the following loops carry out? Assume that i is not
changed in the loop body.
a. for (int i = 1; i <= 10; i++) . . .
b. for (int i = 0; i < 10; i++) . . .
c. for (int i = 10; i > 0; i--) . . .
d. for (int i = -10; i <= 10; i++) . . .
e. for (int i = 10; i >= 0; i++) . . .
f. for (int i = -10; i <= 10; i = i + 2) . . .
g. for (int i = -10; i <= 10; i = i + 3) . . .
•• R4.11 Write pseudocode for a program that prints a calendar such as the following:
Su M T W Th F Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
• R4.12 Write pseudocode for a program that prints a Celsius/Fahrenheit conversion table
such as the following:
Celsius | Fahrenheit
--------+-----------
0 | 32
10 | 50
20 | 68
. . . . . .
100 | 212
• R4.13 Write pseudocode for a program that reads a student record, consisting of the stu
dent’s first and last name, followed by a sequence of test scores and a sentinel of –1.
The program should print the student’s average score. Then provide a trace table for
this sample input:
Harry Morgan 94 71 86 95 -1
•• R4.14 Write pseudocode for a program that reads a sequence of student records and prints
the total score for each student. Each record has the student’s first and last name,
followed by a sequence of test scores and a sentinel of –1. The sequence is terminated
by the word END. Here is a sample sequence:
Harry Morgan 94 71 86 95 -1
Sally Lin 99 98 100 95 90 -1
END
• R4.18 What do the following loops print? Work out the answer by tracing the code, not by
using the computer.
a. int s = 1;
for (int n = 1; n <= 5; n++)
{
s = s + n;
System.out.print(s + " ");
}
b. int s = 1;
for (int n = 1; s <= 10; System.out.print(s + " "))
{
n = n + 2;
s = s + n;
}
c. int s = 1;
int n;
for (n = 1; n <= 5; n++)
{
s = s + n;
n++;
}
System.out.print(s + " " + n);
Review Exercises 187
• R4.19 What do the following program segments print? Find the answers by tracing the
code, not by using the computer.
a. int n = 1;
for (int i = 2; i < 5; i++) { n = n + i; }
System.out.print(n);
b. int i;
double n = 1 / 2;
for (i = 2; i <= 5; i++) { n = n + 1.0 / i; }
System.out.print(i);
c. double x = 1;
double y = 1;
int i = 0;
do
{
y = y / 2;
x = x + y;
i++;
}
while (x < 1.8);
System.out.print(i);
d. double x = 1;
double y = 1;
int i = 0;
while (y >= 1.5)
{
x = x / 2;
y = x + y;
i++;
}
System.out.print(i);
•• R4.20 Give an example of a for loop where symmetric bounds are more natural. Give an
example of a for loop where asymmetric bounds are more natural.
• R4.21 Add a storyboard panel for the conversion program in Section 4.6 on page 162 that
shows a scenario where a user enters incompatible units.
• R4.22 In Section 4.6, we decided to show users a list of all valid units in the prompt. If the
program supports many more units, this approach is unworkable. Give a storyboard
panel that illustrates an alternate approach: If the user enters an unknown unit, a list
of all known units is shown.
• R4.23 Change the storyboards in Section 4.6 to support a menu that asks users whether
they want to convert units, see program help, or quit the program. The menu should
be displayed at the beginning of the program, when a sequence of values has been
converted, and when an error is displayed.
• R4.24 Draw a flow chart for a program that carries out unit conversions as described in
Section 4.6.
•• R4.25 In Section 4.7.5, the code for finding the largest and smallest input initializes the
largest and smallest variables with an input value. Why can’t you initialize them
with zero?
• R4.26 What are nested loops? Give an example where a nested loop is typically used.
188 Chapter 4 Loops
P r o g r a mmi n g E x e r ci s e s
•• P4.4 Complete the program in How To 4.1 on page 169. Your program should read twelve
temperature values and print the month with the highest temperature.
Programming Exercises 189
•• P4.5 Write a program that reads a set of floating-point values. Ask the user to enter the
values, then print
• the average of the values.
• the smallest of the values.
• the largest of the values.
• the range, that is the difference between the smallest and largest.
Of course, you may only prompt for the values once.
• P4.6 Translate the following pseudocode for finding the minimum value from a set of
inputs into a Java program.
Set a Boolean variable "first" to true.
While another value has been read successfully
If first is true
Set the minimum to the value.
Set first to false.
Else if the value is less than the minimum
Set the minimum to the value.
Print the minimum.
••• P4.7 Translate the following pseudocode for randomly permuting the characters in a
string into a Java program.
Read a word.
Repeat word.length() times
Pick a random position i in the word, but not the last position.
Pick a random position j > i in the word.
Swap the letters at positions j and i.
Print the word.
To swap the letters, construct substrings as follows:
• P4.8 Write a program that reads a word and prints each character of the word on a sepa
rate line. For example, if the user provides the input "Harry", the program prints
H
a
r
r
y
•• P4.9 Write a program that reads a word and prints the word in reverse. For example, if the
user provides the input "Harry", the program prints
yrraH
• P4.10 Write a program that reads a word and prints the number of vowels in the word. For
this exercise, assume that a e i o u y are vowels. For example, if the user provides the
input "Harry", the program prints 2 vowels.
190 Chapter 4 Loops
••• P4.11 Write a program that reads a word and prints the number of syllables in the word.
For this exercise, assume that syllables are determined as follows: Each sequence of
adjacent vowels a e i o u y, except for the last e in a word, is a syllable. However, if
that algorithm yields a count of 0, change it to 1. For example,
Word Syllables
Harry 2
hairy 2
hare 1
the 1
••• P4.12 Write a program that reads a word and prints all substrings, sorted by length. For
example, if the user provides the input "rum", the program prints
r
u
m
ru
um
rum
•• P4.14 Write a program that reads a number and prints all of its binary digits: Print the
remainder number % 2, then replace the number with number / 2. Keep going until the
number is 0. For example, if the user provides the input 13, the output should be
1
0
1
1
•• P4.15 Mean and standard deviation. Write a program that reads a set of floating-point data
values. Choose an appropriate mechanism for prompting for the end of the data set.
When all values have been read, print out the count of the values, the average, and
the standard deviation. The average of a data set {x1, . . ., xn} is x = ∑ xi n , where
∑ xi = x1 + … + xn is the sum of the input values. The standard deviation is
∑ ( xi − x )
2
s=
n−1
However, this formula is not suitable for the task. By the time the program has
computed x , the individual xi are long gone. Until you know how to save these
values, use the numerically less stable formula
∑ xi2 − n1 (∑ xi )
2
s=
n−1
You can compute this quantity by keeping track of the count, the sum, and the sum
of squares as you process the input values.
Programming Exercises 191
f1 = 1
f2 = 1
fn = fn −1 + fn − 2
Reformulate that as
Fibonacci numbers describe the
fold1 = 1; growth of a rabbit population.
fold2 = 1;
fnew = fold1 + fold2;
After that, discard fold2, which is no longer needed, and set fold2 to fold1 and fold1 to
fnew. Repeat an appropriate number of times.
Implement a program that prompts the user for an integer n and prints the nth
Fibonacci number, using the above algorithm.
••• P4.17 Factoring of integers. Write a program that asks the user for an integer and then
prints out all its factors. For example, when the user enters 150, the program should
print
2
3
5
5
••• P4.18 Prime numbers. Write a program that prompts the user for an integer and then prints
out all prime numbers up to that integer. For example, when the user enters 20, the
program should print
2
3
5
7
11
13
17
19
Recall that a number is a prime number if it is not divisible by any number except 1
and itself.
• P4.19 Write a program that prints a multiplication table, like this:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
. . .
10 20 30 40 50 60 70 80 90 100
•• P4.20 Write a program that reads an integer and displays, using asterisks, a filled and hol
low square, placed next to each other. For example if the side length is 5, the program
should display
***** *****
***** * *
***** * *
***** * *
***** *****
192 Chapter 4 Loops
•• P4.21 Write a program that reads an integer and displays, using asterisks, a filled diamond
of the given side length. For example, if the side length is 4, the program should dis
play
*
***
*****
*******
*****
***
*
••• P4.22 The game of Nim. This is a well-known game with a number of variants. The fol
lowing variant has an interesting winning strategy. Two players alternately take
marbles from a pile. In each move, a player chooses how many marbles to take. The
player must take at least one but at most half of the marbles. Then the other player
takes a turn. The player who takes the last marble loses.
Write a program in which the computer plays against a human opponent. Generate a
random integer between 10 and 100 to denote the initial size of the pile. Generate a
random integer between 0 and 1 to decide whether the computer or the human takes
the first turn. Generate a random integer between 0 and 1 to decide whether the
computer plays smart or stupid. In stupid mode the computer simply takes a random
legal value (between 1 and n/2) from the pile whenever it has a turn. In smart mode
the computer takes off enough marbles to make the size of the pile a power of two
minus 1—that is, 3, 7, 15, 31, or 63. That is always a legal move, except when the size
of the pile is currently one less than a power of two. In that case, the computer makes
a random legal move.
You will note that the computer cannot be beaten in smart mode when it has the first
move, unless the pile size happens to be 15, 31, or 63. Of course, a human player who
has the first turn and knows the winning strategy can win against the computer.
•• P4.23 The Drunkard’s Walk. A drunkard in a grid of streets randomly picks one of four
directions and stumbles to the next intersection, then again randomly picks one of
four directions, and so on. You might think that on average the drunkard doesn’t
move very far because the choices cancel each other out, but that is actually not the
case.
Represent locations as integer pairs (x, y). Implement the drunkard’s walk over 100
intersections, starting at (0, 0), and print the ending location.
•• P4.24 The Monty Hall Paradox. Marilyn vos Savant described the following problem
(loosely based on a game show hosted by Monty Hall) in a popular magazine: “Sup
pose you’re on a game show, and you’re given the choice of three doors: Behind one
door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who
knows what’s behind the doors, opens another door, say No. 3, which has a goat.
He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to
switch your choice?”
Ms. vos Savant proved that it is to your advantage, but many of her readers, includ
ing some mathematics professors, disagreed, arguing that the probability would not
change because another door was opened.
Your task is to simulate this game show. In each iteration, randomly pick a door
number between 1 and 3 for placing the car. Randomly have the player pick a door.
Randomly have the game show host pick a door having a goat (but not the door that
Programming Exercises 193
the player picked). Increment a counter for strategy 1 if the player wins by switching
to the host’s choice, and increment a counter for strategy 2 if the player wins by
sticking with the original choice. Run 1,000 iterations and print both counters.
• P4.25 A simple random generator is obtained by the formula
( )
rnew = a ⋅ rold + b %m
and then setting rold to rnew. If m is chosen as 232, then you can compute
rnew = a ⋅ rold + b
Figure 9
The Buffon Needle Experiment
For the Buffon needle experiment, you must generate two random numbers: one to
describe the starting position and one to describe the angle of the needle with the
x-axis. Then you need to test whether the needle touches a grid line.
Generate the lower point of the needle. Its x-coordinate is irrelevant, and you may
assume its y-coordinate ylow to be any random number between 0 and 2. The angle a
between the needle and the x-axis can be any value between 0 degrees and 180
degrees (p radians). The upper end of the needle has y-coordinate
yhigh = ylow + sin α
The needle is a hit if yhigh is at least 2, as shown in Figure 10. Stop after 10,000 tries
and print the quotient tries/hits. (This program is not suitable for computing the
value of p. You need p in the computation of the angle.)
yhigh
2
ylow α
Figure 10
A Hit in the Buffon Needle Experiment 0
194 Chapter 4 Loops
•• Science P4.33 In a predator-prey simulation, you compute the populations of predators and prey,
using the following equations:
(
preyn +1 = preyn × 1 + A − B × predn )
predn +1 = predn × (1 − C + D × preyn )
Here, A is the rate at which prey birth exceeds natural
death, B is the rate of predation, C is the rate at which
predator deaths exceed births without food, and D repre
sents predator increase in the presence of food.
Write a program that prompts users for these rates, the
initial population sizes, and the number of periods. Then
print the populations for the given number of periods. As
inputs, try A = 0.1, B = C = 0.01, and D = 0.00002 with
initial prey and predator populations of 1,000 and 20.
•• Science P4.34 Projectile flight. Suppose a cannonball is propelled straight into the air with a starting
velocity v0. Any calculus book will state that the position of the ball after t seconds is
s(t ) = − 1 gt 2 + v0t, where g = 9.81 m s2 is the gravitational force of the earth. No
2
calculus textbook ever mentions why someone would want to carry out such an
obviously dangerous experiment, so we will do it in the safety of the computer.
In fact, we will confirm the theorem
from calculus by a simulation. In our
simulation, we will consider how the
ball moves in very short time intervals
Δt. In a short time interval the velocity v
is nearly constant, and we can compute
the distance the ball moves as Δs = vΔt.
In our program, we will simply set
const double DELTA_T = 0.01;
and update the position by
s = s + v * DELTA_T;
The velocity changes constantly—in fact, it is reduced by the gravitational force of
the earth. In a short time interval, Δv = –gΔt, we must keep the velocity updated as
v = v - g * DELTA_T;
In the next iteration the new velocity is used to update the distance.
Now run the simulation until the cannonball falls back to the earth. Get the initial
velocity as an input (100 m̸s is a good value). Update the position and velocity 100
times per second, but print out the position only every full second. Also printout the
values from the exact formula s(t ) = − 1 gt 2 + v0t for comparison.
2
Note: You may wonder whether there is a benefit to this simulation when an exact
formula is available. Well, the formula from the calculus book is not exact. Actually,
the gravitational force diminishes the farther the cannonball is away from the surface
of the earth. This complicates the algebra sufficiently that it is not possible to give an
exact formula for the actual motion, but the computer simulation can simply be
extended to apply a variable gravitational force. For cannonballs, the calculus-book
formula is actually good enough, but computers are necessary to compute accurate
trajectories for higher-flying objects such as ballistic missiles.
196 Chapter 4 Loops
••• Science P4.35 A simple model for the hull of a ship is given by
B 2x z
2 2
y = 1 − 1 −
2 L T
where B is the beam, L is the length, and T is the draft. (Note: There are two values of
y for each x and z because the hull is symmetric from starboard to port.)
+
– Vs = 40 V Rs = 8 Ω
The symbol used to represent the transformer is intended to suggest two coils of
wire. The parameter n of the transformer is called the “turns ratio” of the trans
former. (The number of times that a wire is wrapped around the core to form a coil is
called the number of turns in the coil. The turns ratio is literally the ratio of the
number of turns in the two coils of wire.)
When designing the circuit, we are concerned primarily with the value of the power
delivered to the speakers—that power causes the speakers to produce the sounds we
want to hear. Suppose we were to connect the speakers directly to the amplifier
without using the transformer. Some fraction of the power available from the
amplifier would get to the speakers. The rest of the available power would be lost in
the amplifier itself. The transformer is added to the circuit to increase the fraction of
the amplifier power that is delivered to the speakers.
The power, Ps , delivered to the speakers is calculated using the formula
2
nVs
Ps = Rs
n 2 R + R
0 s
Write a program that models the circuit shown and varies the turns ratio from 0.01 to
2 in 0.01 increments, then determines the value of the turns ratio that maximizes the
power delivered to the speakers.
• Graphics P4.38 Write a program to plot the following face.
• Graphics P4.39 Write a graphical application that displays a checkerboard with 64 squares, alternat
ing white and black.
••• Graphics P4.40 Write a graphical application that draws a spiral, such as the following:
•• Graphics P4.41 It is easy and fun to draw graphs of curves with the Java graphics library. Simply
draw 100 line segments joining the points (x, f(x)) and (x + d, f(x + d)), where x
ranges from xmin to xmax and d = ( xmax − xmin ) 100.
Draw the curve f ( x) = 0.00005 x3 − 0.03 x 2 + 4 x + 200, where x ranges from 0 to
400 in this fashion.
••• Graphics P4.42 Draw a picture of the “four-leaved rose” whose equation in polar coordinates is
r = cos( 2θ ) . Let q go from 0 to 2p in 100 steps. Each time, compute r and then
compute the (x, y) coordinates from the polar coordinates by using the formula
x = r ⋅ cos(θ ), y = r ⋅ sin(θ )
198 Chapter 4 Loops
A n s w e r s t o S e lf - C h e c k Q u e s t i o n s
be initialized with some value—otherwise the 39. 60: The outer loop is executed 10 times, and
compiler will complain about a possibly unini the inner loop 6 times.
tialized variable. 40. 0123
34. The loop will stop when a match is found, but 1234
2345
you cannot access the match because neither
position nor ch are defined outside the loop. 41. for (int i = 1; i <= 3; i++)
{
35. Start the loop at the end of string: for (int j = 1; j <= 4; j++)
boolean found = false; {
int i = str.length() - 1; System.out.print("[]");
while (!found && i >= 0) }
{ System.out.println();
char ch = str.charAt(i); }
if (ch == ' ') { found = true; } 42. Compute (int) (Math.random() * 2), and use 0
else { i--; }
} for heads, 1 for tails, or the other way around.
36. The initial call to in.nextDouble() fails, termi 43. Compute (int) (Math.random() * 4) and asso
nating the program. One solution is to do all ciate the numbers 0 . . . 3 with the four suits.
input in the loop and introduce a Boolean vari Then compute (int) (Math.random() * 13) and
able that checks whether the loop is entered for associate the numbers 0 . . . 12 with Jack, Ace, 2
the first time. . . . 10, Queen, and King.
double input = 0; 44. We need to call it once for each die. If we
boolean first = true; printed the same value twice, the die tosses
while (in.hasNextDouble()) would not be independent.
{
45. The call will produce a value between 2 and
double previous = input;
input = in.nextDouble(); 12, but all values have the same probability.
if (first) { first = false; } When throwing a pair of dice, the number 7 is
else if (input == previous) six times as likely as the number 2. The correct
{ formula is
System.out.println("Duplicate input");
} int sum = (int) (Math.random() * 6) + (int)
} (Math.random() * 6) + 2;
46. Math.random() * 100.0
37. All values in the inner loop should be dis
played on the same line.
38. Change lines 13, 18, and 30 to for (int n = 0;
n <= NMAX; n++). Change NMAX to 5.