0% found this document useful (0 votes)
3 views

Loops Notes

Uploaded by

Vivaan Grover
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Loops Notes

Uploaded by

Vivaan Grover
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Chapter 4

Loops

Chapter Goals

To implement while, for, and do loops


To hand-trace the execution of a program
To become familiar with common
loop algorithms
To understand nested loops
To implement programs that read and process data sets
To use a computer for simulations

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.

4.1 The while Loop


In this section, you will learn about loop statements that
repeatedly execute instructions until a goal has been
reached.
Recall the investment problem from Chapter 1. You
put $10,000 into a bank account that earns 5 percent inter­
est per year. How many years does it take for the account Because the interest
balance to be double the original investment? earned also earns interest,
In Chapter 1 we developed the following algorithm for a bank balance grows
this problem: exponentially.

Start with a year value of 0, a column for the interest, and a balance of $10,000.

year interest balance


0 $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”.

In a particle accelerator, subatomic particles


traverse a loop-shaped tunnel multiple times,
gaining the speed required for physical experiments.
Similarly, in computer science, statements in a
loop are executed while a condition is true.

140
4.1 The while Loop 141

Figure 1 Flowchart of a while Loop

balance < False


TARGET?

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
}

As long as the condition remains true, the statements


Calculate
inside the while statement are executed. These state­ interest
ments are called the body of the while statement.
In our case, we want to increment the year coun­
ter and add interest while the balance is less than the
target balance of $20,000: Add interest
to balance
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
}

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

Syntax 4.1 while Statement

Syntax while (condition)


{
statements
}

This variable is declared outside the loop


Beware of “off-by-one”
and updated in the loop.
errors in the loop condition.
double balance = 0; See page 145.
If the condition .
never becomes false, . Don’t put a semicolon here!
an infinite loop occurs. . See page 86.
See page 145. while (balance < TARGET)
{
These statements
double interest = balance * RATE / 100;
are executed while
This variable is created balance = balance + interest;
the condition is true.
in each loop iteration. }

Braces are not required if the body contains


Lining up braces
a single statement, but it’s good to always use them.
is a good idea.
See page 86.
See page 86.
142 Chapter 4 Loops

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 vari­able is used for all iterations of the loop.

1 Check the loop condition The condition is true


while (balance < TARGET)
{
balance = 10000
year++;
double interest = balance * RATE / 100;
year = 0 balance = balance + interest;
}

2 Execute the statements in the loop


while (balance < TARGET)
{
balance = 10500
year++;
double interest = balance * RATE / 100;
year = 1 balance = balance + interest;
}
interest = 500

3 Check the loop condition again The condition is still true


while (balance < TARGET)
{
balance = 10500
year++;
double interest = balance * RATE / 100;
year = 1 balance = balance + interest;
}
.
.
.

4 After 15 iterations The condition is


while (balance < TARGET) no longer true
{
balance = 20789.28
year++;
double interest = balance * RATE / 100;
year = 15 balance = balance + interest;
}

5 Execute the statement following the loop


while (balance < TARGET)
balance = 20789.28 {
year++;
Figure 2 double interest = balance * RATE / 100;
year = 15
balance = balance + interest;
Execution of the
}
DoubleInvestment
System.out.println(year);
Loop
4.1 The while Loop 143

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

Table 1 while Loop Examples


Loop Output Explanation

i = 0; sum = 0; 1 1 When sum is 10, the loop condition is


while (sum < 10) 2 3 false, and the loop ends.
{ 3 6
i++; sum = sum + i; 4 10
Print i and sum;
}

i = 0; sum = 0; 1 -1 Because sum never reaches 10, this is an


while (sum < 10) 2 -3 “infinite loop” (see Common Error 4.2
{ 3 -6 on page 145).
i++; sum = sum - i; 4 -10
Print i and sum; . . .
}

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;
}

i = 0; sum = 0; (No output) The programmer probably thought,


while (sum >= 10) “Stop when the sum is at least 10.”
{ However, the loop condition controls
i++; sum = sum + i; when the loop is executed, not when it
Print i and sum; ends (see Common Error 4.1 on
} page 144).
i = 0; sum = 0; (No output, program Note the semicolon before the {.
while (sum < 10) ; does not terminate) This loop has an empty body. It runs
{ forever, checking whether sum < 0 and
i++; sum = sum + i; doing nothing in the body.
Print i and sum;
}

Common Error 4.1 Don’t Think “Are We There Yet?”


When doing something repetitive, most of us want to know when
we are done. For exam­ple, you may think, “I want to get at least
$20,000,” and set the loop condition to
balance >= TARGET
But the while loop thinks the opposite: How long am I allowed to
keep going? The correct loop condition is
while (balance < TARGET)
In other words: “Keep at it while the balance is less than the target.”
When writing a loop condition, don’t ask, “Are we there yet?”
The condition determines how long the loop will keep going.
4.1 The while Loop 145

Common Error 4.2 Infinite Loops


A very annoying loop error is an infinite loop: a loop that
runs forever and can be stopped only by killing the program
or restarting the computer. If there are output statements
in the program, then reams and reams of output flash by on
the screen. Otherwise, the program just sits there and hangs,
seeming to do nothing. On some systems, you can kill a hang­
ing program by hitting Ctrl + C. On others, you can close the
window in which the program runs.
A common reason for infinite loops is forgetting to update
the variable that controls the loop:
int year = 1;
while (year <= 20) Like this hamster who can’t
{ stop running in the tread­mill,
double interest = balance * RATE / 100; an infinite loop never ends.
balance = balance + interest;
}
Here the programmer forgot to add a year++ command in the loop. As a result, the year always
stays at 1, and the loop never comes to an end.
Another common reason for an infinite loop is accidentally incrementing a counter that
should be decremented (or vice versa). Consider this example:
int year = 20;
while (year > 0)
{
double interest = balance * RATE / 100;
balance = balance + interest;
year++;
}
The year variable really should have been decremented, not incremented. This is a common
error because increment­ing counters is so much more common than decrementing that your
fingers may type the ++ on autopilot. As a con­sequence, year is always larger than 0, and the
loop never ends. (Actually, year may eventually exceed the largest representable positive inte­
ger and wrap around to a negative number. Then the loop ends—of course, with a com­pletely
wrong result.)

Common Error 4.3 Off-by-One Errors


Consider our computation of the number of years that are required to double an investment:
int year = 0;
while (balance < TARGET)
{
year++;
balance = balance * (1 + RATE / 100);
}
System.out.println("The investment doubled after "
+ year + " years.");
Should year start at 0 or at 1? Should you test for balance < TARGET or for balance <= TARGET? It is
easy to be off by one in these expressions.
146 Chapter 4 Loops

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.

Random Fact 4.1 The First Bug


According to legend, The pioneering computer scientist grams right. I can remember the exact
the first bug was Maurice Wilkes wrote, “Somehow, at instant in time at which it dawned on
found in the Mark II, a huge electrome­ the Moore School and afterwards, one me that a great part of my future life
chanical computer at Harvard Univer­ had always assumed there would be would be spent finding mistakes in my
sity. It really was caused by a bug—a no particular difficulty in getting pro­ own programs.”
moth was trapped in a relay switch.
Actually, from the note that the
operator left in the log book next to
the moth (see the photo), it appears as
if the term “bug” had already been in
active use at the time.

The First Bug


4.2 Problem Solving: Hand-Tracing 147

4.2 Problem Solving: Hand-Tracing


Hand-tracing is a
In Programming Tip 3.5, you learned about the method of hand-tracing. When you
simulation of code hand-trace code or pseudocode, you write the names of the variables on a sheet of
execution in which paper, mentally execute each step of the code and update the variables.
you step through
instructions and
It is best to have the code written or printed on a sheet of paper. Use a marker,
track the values of such as a paper clip, to mark the current line. Whenever a variable changes, cross out
the variables. the old value and write the new value below. When a program produces output, also
write down the output in another column.
Consider this example. What value is displayed?
int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);

There are three variables: n, sum, and digit.

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 argu­ments 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);

Now check the loop condition again.


int n = 1729;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
System.out.println(sum);

Because n is still greater than zero, repeat


n sum digit
the loop. Now digit becomes 2, sum is set
to 9 + 2 = 11, and n is set to 17. 1729 0
172 9 9
17 11 2

Repeat the loop once again, setting digit


n sum digit
to 7, sum to 11 + 7 = 18, and n to 1.
1729 0
172 9 9
17 11 2
1 18 7

Enter the loop for one last time. Now


n sum digit
digit is set to 1, sum to 19, and n becomes
zero. 1729 0
172 9 9
17 11 2
1 18 7
0 19 1
4.2 Problem Solving: Hand-Tracing 149

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 itera­tion:
• 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.

4.3 The for Loop


The for loop is
It often happens that you want to execute a sequence of statements a given number
used when a of times. You can use a while loop that is controlled by a counter, as in the following
value runs from a example:
starting point to an
ending point with a int counter = 1; // Initialize the counter
constant increment while (counter <= 10) // Check the counter
or decrement. {
System.out.println(counter);
counter++; // Update the counter
}

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

for (int counter = 1; counter <= 10; counter++)


{
System.out.println(counter);
}

Some people call this loop count-controlled. In con­


trast, the while loop of the preceding section can be
called an event-controlled loop because it executes
until an event occurs; namely that the balance
reaches the target. Another commonly used term
for a count-controlled loop is definite. You know
from the outset that the loop body will be executed
a definite number of times; ten times in our example.
In contrast, you do not know how many iterations
it takes to accumulate a target balance. Such a loop is
called indefinite.
The for loop neatly groups the initialization, con­
dition, and update expressions together. However, it You can visualize the for loop as
is important to realize that these expressions are not an orderly sequence of steps.

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 }

3 Execute loop body


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 }

5 Check condition again


for (int counter = 1; counter <= 10; counter++)
{
Figure 3 System.out.println(counter);
Execution of a counter = 2 }
for Loop
152 Chapter 4 Loops

Syntax 4.2 for Statement

Syntax for (initialization; condition; update)


{
statements
}
These three
expressions should be related.
See page 155.

This initialization The condition is This update is


happens once checked before executed after
before the loop starts. each iteration. each iteration.

for (int i = 5; i <= 10; i++)


{
The variable i is sum = sum + i; This loop executes 6 times.
defined only in this for loop. } See page 156.
See page 153.

A for loop can count down instead of up:


for (int counter = 10; counter >= 0; counter--) . . .

The increment or decrement need not be in steps of 1:


for (int counter = 0; counter <= 10; counter = counter + 2) . . .

See Table 2 for additional variations.


So far, we have always declared the counter variable in the loop initialization:
for (int counter = 1; counter <= 10; counter++)
{
. . .
}
// counter no longer declared here

Table 2 for Loop Examples


Loop Values of i Comment

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.

for (i = 0; i < 9; i = i + 2) 02468 Use i = i + 2 for a step size of 2.

for (i = 0; i != 9; i = i + 2) 0 2 4 6 8 10 12 14 … You can use < or <= instead of != to avoid


(infinite loop) this problem.
for (i = 1; i <= 20; i = i * 2) 1 2 4 8 16 You can specify any rule for modifying i,
such as doubling it in every step.
for (i = 0; i < str.length(); i++) 0 1 2 … until the last valid In the loop body, use the expression
index of the string str str.charAt(i) to get the ith character.
4.3 The for Loop 153

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 ?

The for loop pattern applies because the variable


year starts at 1 and then moves in constant incre­
True
ments until it reaches the target:
for (int year = 1; year <= nyears; year++) Update balance;
{ Print year and
Update balance. balance
Print year and balance.
}

Following is the complete program. Figure 4


shows the corresponding flowchart.
year++

Figure 4 Flowchart of a for Loop

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

12 double balance = INITIAL_BALANCE;


13
14 System.out.print("Enter number of years: ");
15 Scanner in = new Scanner(System.in);
16 int nyears = in.nextInt();
17
18 // Print the table of balances for each year
19
20 for (int year = 1; year <= nyears; year++)
21 {
22 double interest = balance * RATE / 100;
23 balance = balance + interest;
24 System.out.printf("%4d %10.2f\n", year, balance);
25 }
26 }
27 }

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 incre­ment 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 exam­ple:
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 itera­tion. In some loop iterations, counter is incremented once, in others twice.
This goes against the intuition of a pro­grammer 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

Programming Tip 4.3 Count Iterations


Finding the correct lower and upper bounds for an iteration can be confusing. Should you
start at 0 or at 1? Should you use <= b or < b as a termination condition?
Counting the number of iterations is a very useful device for better understanding a loop.
Counting is easier for loops with asymmetric bounds. The loop
for (int i = a; i < b; i++)
is executed b - a times. For example, the loop traversing the characters in a string,

for (int i = 0; i < str.length(); i++)


runs str.length() times. That makes perfect sense, because there are str.length() characters in
a string.
The loop with symmetric bounds,
for (int i = a; i <= b; i++)
is executed b - a + 1 times. That “+1” is the source of many programming errors.
For example,
for (int i = 0; i <= 10; i++)
runs 11 times. Maybe that is what you want; if not, start at 1 or use < 10.
One way to visualize this “+1” error is
by looking at a fence. Each section has one
fence post to the left, and there is a final post
on the right of the last section. Forgetting to
count the last value is often called a “fence
post error”.

How many posts do you need for a fence


with four sections? It is easy to be “off by one”
with problems such as this one.

4.4 The do Loop


The do loop is
Sometimes you want to execute the body of a loop at least once and perform the loop
appropriate when test after the body is executed. The do loop serves that purpose:
the loop body
do
must be executed
at least once. {
statements
}
while (condition);

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

Figure 5 Flowchart of a do Loop

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.

Programming Tip 4.4 Flowcharts for Loops


In Section 3.5, you learned how to use flowcharts to visualize the flow of control in a program.
There are two types of loops that you can include in a flowchart; they correspond to a while
loop and a do loop in Java. They differ in the placement of the condition—either before or after
the loop body.

False
Condition? Loop body

True

Loop body True


Condition?

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

4.5 Application: Processing Sentinel Values


In this section, you will learn how to write loops that read and process a sequence of
input values.
A sentinel value
Whenever you read a sequence of inputs, you
denotes the end of a need to have some method of indicating the end
data set, but it is not of the sequence. Sometimes you are lucky and no
part of the data.
input value can be zero. Then you can prompt the
user to keep entering numbers, or 0 to finish the
sequence. If zero is allowed but negative numbers
are not, you can use –1 to indicate termination.
Such a value, which is not an actual input,
but serves as a signal for termination, is called a
sentinel.
Let’s put this technique to work in a program
that computes the average of a set of salary values.
In our sample program, we will use –1 as a sentinel.
An employee would surely not work for a negative
salary, but there may be volunteers who work for
free.
Inside the loop, we read an input. If the input is
not –1, we process it. In order to compute the aver­ In the military, a sentinel guards
age, we need the total sum of all salaries, and the a border or passage. In computer
science, a sentinel value denotes
number of inputs.
the end of an input sequence or the
salary = in.nextDouble(); border between input sequences.
if (salary != -1)
{
sum = sum + salary;
count++;
}

We stay in the loop while the sentinel value is not detected.


while (salary != -1)
{
. . .
}

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

6 public class SentinelDemo


7 {
8 public static void main(String[] args)
9 {
10 double sum = 0;
11 int count = 0;
12 double salary = 0;
13 System.out.print("Enter salaries, -1 to finish: ");
14 Scanner in = new Scanner(System.in);
15
16 // Process data until the sentinel is entered
17
18 while (salary != -1)
19 {
20 salary = in.nextDouble();
21 if (salary != -1)
22 {
23 sum = sum + salary;
24 count++;
25 }
26 }
27
28 // Compute and print the average
29
30 if (count > 0)
31 {
32 double average = sum / count;
33 System.out.println("Average salary: " + average);
34 }
35 else
36 {
37 System.out.println("No data");
38 }
39 }
40 }

Program Run
Enter salaries, -1 to finish: 10 10 40 -1
Average salary: 20

You can use a


Some programmers don’t like the “trick” of initializing the input variable with a value
Boolean variable to other than the sen­tinel. Another approach is to use a Boolean variable:
control a loop. Set
System.out.print("Enter salaries, -1 to finish: ");
the variable before
entering the loop, boolean done = false;
then set it to the while (!done)
opposite to leave {
the loop. value = in.nextDouble();
if (value == -1)
{
done = true;
}
else
{
Process value.
}
}

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.

Special Topic 4.2 Redirection of Input and Output


Consider the SentinelDemo program that computes the average
Use input redirection to
value of an input sequence. If you use such a program, then it is read input from a file.
quite likely that you already have the values in a file, and it seems Use output redirection to
a shame that you have to type them all in again. The command capture program output
line interface of your operating system provides a way to link a in a file.
file to the input of a pro­gram, as if all the characters in the file had
actually been typed by a user. If you type
java SentinelDemo < numbers.txt
the program is executed, but it no longer expects input from the keyboard. All input com­
mands get their input from the file numbers.txt. This process is called input redirection.
Input redirection is an excellent tool for testing programs. When you develop a program
and fix its bugs, it is bor­ing to keep entering the same input every time you run the program.
Spend a few minutes putting the inputs into a file, and use redirection.
You can also redirect output. In this program, that is not terribly useful. If you run
java SentinelDemo < numbers.txt > output.txt
the file output.txt contains the input prompts and the output, such as
Enter salaries, -1 to finish: Enter salaries, -1 to finish:
Enter salaries, -1 to finish: Enter salaries, -1 to finish:
Average salary: 15
However, redirecting output is obviously useful for programs that produce lots of output.
You can format or print the file con­taining the output.

Video E xamp le 4.1 Evaluating a Cell Phone Plan


In this Video Example, you will learn how to design a
program that computes the cost of a cell phone plan
from actual usage data.

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


162 Chapter 4 Loops

4.6 Problem Solving: Storyboards


When you design a program that interacts with a user, you need to make a plan for
that interaction. What information does the user provide, and in which order? What
information will your program display, and in which format? What should happen
when there is an error? When does the program quit?
A storyboard consists
This planning is similar to the development of a movie or a computer game, where
of annotated storyboards are used to plan action sequences. A storyboard is made up of panels that
sketches for each show a sketch of each step. Annota­tions explain what is happening and note any spe­
step in an action
sequence.
cial situations. Storyboards are also used to develop software—see Figure 6.
Making a storyboard is very helpful when you begin designing a program. You
need to ask yourself which information you need in order to compute the answers
that the program user wants. You need to decide how to present those answers. These
are important considerations that you want to settle before you design an algorithm
for computing the answers.
Developing a
Let’s look at a simple example. We want to write a program that helps users with
storyboard helps you questions such as “How many tablespoons are in a pint?” or “How many inches are
understand the 30 centimeters?”
inputs and outputs
that are required for
What information does the user provide?
a program.
• The quantity and unit to convert from
• The unit to convert to
What if there is more than one quantity? A user may have a whole table of centimeter
values that should be converted into inches.
What if the user enters units that our program doesn’t know how to handle, such
as ångström?
What if the user asks for impossible conversions, such as inches to gallons?

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

Converting a Sequence of Values


What unit do you want to convert from? cm
What unit do you want to convert to? in
Enter values, terminated by zero Allows conversion of multiple values
30
30 cm = 11.81 in
100 Format makes clear what got converted
100 cm = 39.37 in
0
What unit do you want to convert from?

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.

Handling Unknown Units (needs improvement)


What unit do you want to convert from? cm
What unit do you want to convert to? inches
Sorry, unknown unit.
What unit do you want to convert to? inch
Sorry, unknown unit.
What unit do you want to convert to? grrr

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

Exiting the Program


From unit (in, ft, mi, mm, cm, m, km, oz, lb, g, kg, tsp, tbsp, pint, gal): cm
To unit: in
Enter values, terminated by zero
30
30 cm = 11.81 in
0 Sentinel triggers the prompt to exit
More conversions (y, n)? n
(Program exits)

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.

Make storyboards for an equivalent interface in a Java program. Show a scenario


in which all goes well, and show the handling of two kinds of errors.
28. Consider a modification of the program in Self Check 26. Suppose we want to
drop the lowest score before computing the average. Provide a storyboard for
the situation in which a user only provides one score.
29. What is the problem with implementing the following storyboard in Java?

Computing Multiple Averages


Enter scores: 90 80 90 100 80
The average is 88
Enter scores: 100 70 70 100 80
The average is 88
-1 is used as a sentinel to exit the program
Enter scores: -1
(Program exits)

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

4.7 Common Loop Algorithms


In the following sections, we discuss some of the most common algorithms that are
implemented as loops. You can use them as starting points for your loop designs.

4.7.1 Sum and Average Value

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;
}

4.7.2 Counting Matches

To count values that


You often want to know how many values fulfill a particular condition. For example,
fulfill a condition, you may want to count how many spaces are in a string. Keep a counter, a variable
check all values and that is initialized with 0 and incremented whenever there is a match.
increment a counter
for each match. int spaces = 0;
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
if (ch == ' ')
{
spaces++;
}
}

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++;
}
}

In a loop that counts matches,


a counter is incremented
whenever a match is found.

4.7.3 Finding the First Match

If your goal is to find


When you count the values that fulfill a condition, you need to look at all values.
a match, exit the loop However, if your task is to find a match, then you can stop as soon as the condition is
when the match fulfilled.
is found.
Here is a loop that finds the first space in a string. Because we do not visit all ele­
ments in the string, a while loop is a better choice than a for loop:
boolean found = false;
char ch = '?';
int position = 0;
while (!found && position < str.length())
{
ch = str.charAt(position);
if (ch == ' ') { found = true; }
else { position++; }
}

If a match was found, then found is true, ch is


the first matching character, and position is
the index of the first match. If the loop did
not find a match, then found remains false
after the end of the loop.
Note that the variable ch is declared out-
side the while loop because you may want to
use the input after the loop has finished. If it
had been declared inside the loop body, you When searching, you look at items until a
would not be able to use it outside the loop. match is found.
4.7 Common Loop Algorithms 167

4.7.4 Prompting Until a Match is Found


In the preceding example, we searched a string for a character that matches a condi­
tion. You can apply the same process to user input. Suppose you are asking a user to
enter a positive value < 100. Keep asking until the user provides a correct input:
boolean valid = false;
double input = 0;
while (!valid)
{
System.out.print("Please enter a positive value < 100: ");
input = in.nextDouble();
if (0 < input && input < 100) { valid = true; }
else { System.out.println("Invalid input."); }
}

Note that the variable input is declared outside the while loop because you will want to
use the input after the loop has finished.

4.7.5 Maximum and Minimum

To find the largest


To compute the largest value in a sequence, keep a variable that stores the largest ele­
value, update the ment that you have encountered, and update it when you find a larger one.
largest value seen so
double largest = in.nextDouble();
far whenever you see
a larger one. while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}

This algorithm requires that there is at least one input.


To compute the smallest value, simply reverse the comparison:
double smallest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input < smallest)
{
smallest = input;
}
}

To find the height of the tallest bus rider,


remember the largest value so far, and
update it whenever you see a taller one.
168 Chapter 4 Loops

4.7.6 Comparing Adjacent Values

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();
. . .
}

How can you compare the current input


with the preceding one? At any time, input
contains the current input, overwriting the
previous one.
The answer is to store the previous input,
like this:
double input = 0; When comparing adjacent values, store
while (in.hasNextDouble()) the previous value in a variable.
{
double previous = input;
input = in.nextDouble();
if (input == previous)
{
System.out.println("Duplicate input");
}
}

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.

Ho w To 4.1 Writing a Loop


This How To walks you through the process of implementing a
loop statement. We will illustrate the steps with the following
example problem:
Read twelve temperature values (one for each month), and dis­
play the number of the month with the highest temperature. For
example, according to http://worldclimate.com, the average maxi­
mum temperatures for Death Valley are (in order by month, in
degrees Celsius):
18.2 22.6 26.4 31.1 36.6 42.2 45.7 44.5 40.2 33.1 24.2 17.6
In this case, the month with the highest temperature (45.7 degrees
Celsius) is July, and the program should display 7.

Step 1 Decide what work must be done inside the loop.

Every loop needs to do some kind of repetitive work, such as


• Reading another item.
• Updating a value (such as a bank balance or total).
• Incrementing a counter.
If you can’t figure out what needs to go inside the loop, start by writing down the steps that
you would take if you solved the problem by hand. For example, with the temperature reading
problem, you might write
Read first value.
Read second value.
If second value is higher than the first, set highest temperature to that value, highest month to 2.
Read next value.
If value is higher than the first and second, set highest temperature to that value, highest month to 3.
Read next value.
If value is higher than the highest temperature seen so far, set highest temperature to that value,
highest month to 4.
. . .
Now look at these steps and reduce them to a set of uniform actions that can be placed into the
loop body. The first action is easy:
Read next value.
The next action is trickier. In our description, we used tests “higher than the first”, “higher
than the first and sec­ond”, “higher than the highest temperature seen so far”. We need to settle
on one test that works for all iterations. The last formulation is the most general.
170 Chapter 4 Loops

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

In our example, the variables are


current month
highest value
highest month
We need to be careful how we set up the highest temperature value. We can’t simply set it to
0. After all, our program needs to work with temperature values from Antarctica, all of which
may be negative.
A good option is to set the highest temperature value to the first input value. Of course,
then we need to remember to read in only 11 more values, with the current month starting at 2.
We also need to initialize the highest month with 1. After all, in an Australian city, we may
never find a month that is warmer than January.
Step 5 Process the result after the loop has finished.
In many cases, the desired result is simply a variable that was updated in the loop body. For
example, in our temper­ature program, the result is the highest month. Sometimes, the loop
computes values that contribute to the final result. For example, suppose you are asked to
average the temperatures. Then the loop should compute the sum, not the average. After the
loop has completed, you are ready to compute the average: divide the sum by the number of
inputs.
Here is our complete loop.
Read first value; store as highest value.
highest month = 1
For current month from 2 to 12
Read next value.
If value is higher than the highest value
Set highest value to that value.
Set highest month to current month.

Step 6 Trace the loop with typical examples.


Hand trace your loop code, as described in Section 4.2. Choose example values that are not too
complex—execut­ing the loop 3–5 times is enough to check for the most common errors. Pay
special attention when entering the loop for the first and last time.
Sometimes, you want to make a slight modification to make tracing feasible. For example,
when hand-tracing the investment doubling problem, use an interest rate of 20 percent rather
than 5 percent. When hand-tracing the tem­perature loop, use 4 data values, not 12.
Let’s say the data are 22.6 36.6 44.5 24.2. Here is the walkthrough:

current month current value highest month highest value


1 22.6
2 36.6 2 36.6
3 44.5 3 44.5
4 24.2

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

for (int currentMonth = 2; currentMonth <= 12; currentMonth++)


{
double nextValue = in.nextDouble();
if (nextValue > highestValue)
{
highestValue = nextValue;
highestMonth = currentMonth;
}
}
System.out.println(highestMonth);

Worked Example 4.1 Credit Card Processing


This Worked Example uses a loop to remove spaces from a
credit card number.

4.8 Nested Loops


When the body of a
In Section 3.4, you saw how to nest two if statements. Similarly, complex iterations
loop contains sometimes require a nested loop: a loop inside another loop statement. When pro­
another loop, the cessing tables, nested loops occur naturally. An outer loop iterates over all rows of the
loops are nested. A
typical use of nested
table. An inner loop deals with the columns in the current row.
loops is printing a In this section you will see how to print a table. For simplicity, we will simply print
table with rows the powers of x, xn, as in the table at right.
and columns.
Here is the pseudocode for printing the table: 1 2 3 4
x x x x
Print table header.
For x from 1 to 10 1 1 1 1
Print table row.
2 4 8 16
Print new line.
How do you print a table row? You need to print a 3 9 27 81
value for each expo­nent. This requires a second loop. … … … …
For n from 1 to 4 10 100 1000 10000
Print xn.
This loop must be placed inside the preceding loop. We say that the inner loop is
nested inside the outer loop.

The hour and minute displays in a digital clock are an


exam­ple of nested loops. The hours loop 12 times, and
for each hour, the minutes loop 60 times.

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


4.8 Nested Loops 173

x=1

This loop is nested


False in the outer loop.
x ≤ 10 ?

True
n=1

False n≤4?

True

Print xn

Print new line

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

18 for (int n = 1; n <= NMAX; n++)


19 {
20 System.out.printf("%10s", "x ");
21 }
22 System.out.println();
23
24 // Print table body
25
26 for (double x = 1; x <= XMAX; x++)
27 {
28 // Print table row
29
30 for (int n = 1; n <= NMAX; n++)
31 {
32 System.out.printf("%10.0f", Math.pow(x, n));
33 }
34 System.out.println();
35 }
36 }
37 }

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.

Table 3 Nested Loop Examples


Nested Loops Output Explanation

for (i = 1; i <= 3; i++) **** Prints 3 rows of 4


{ **** asterisks each.
for (j = 1; j <= 4; j++) { Print "*" } ****
System.out.println();
}

for (i = 1; i <= 4; i++) *** Prints 4 rows of 3


{ *** asterisks each.
for (j = 1; j <= 3; j++) { Print "*" } ***
System.out.println(); ***
}

for (i = 1; i <= 4; i++) * Prints 4 rows of


{ ** lengths 1, 2, 3, and 4.
for (j = 1; j <= i; j++) { Print "*" } ***
System.out.println(); ****
}

for (i = 1; i <= 3; i++) -*-*- Prints asterisks in


{ -*-*- even columns,
for (j = 1; j <= 5; j++) -*-*- dashes in odd
{ columns.
if (j % 2 == 0) { Print "*" }
else { Print "-" }
}
System.out.println();
}

for (i = 1; i <= 3; i++) * * * Prints a


{ * * checkerboard
for (j = 1; j <= 5; j++) * * * pattern.
{
if (i % 2 == j % 2) { Print "*" }
else { Print " " }
}
System.out.println();
}

Worked Example 4.2 Manipulating the Pixels in an Image


This Worked Example shows how to use nested loops for
manipulating the pix­els in an image. The outer loop tra­
verses the rows of the image, and the inner loop accesses
each pixel of a row.

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


176 Chapter 4 Loops

4.9 Application: Random Numbers


and Simulations
In a simulation, you
A simulation program uses the computer to simulate an activity in the real world (or
use the computer to an imaginary one). Simulations are commonly used for predicting climate change,
simulate an activity. analyzing traffic, picking stocks, and many other applications in science and busi­
ness. In many simulations, one or more loops are used to modify the state of a system
and observe the changes. You will see examples in the following sections.

4.9.1 Generating Random Numbers


Many events in the real world are difficult to predict with absolute precision, yet we
can sometimes know the average behavior quite well. For example, a store may know
from experience that a customer arrives every five minutes. Of course, that is an aver­
age—customers don’t arrive in five minute intervals. To accurately model customer
traffic, you want to take that random fluctuation into account. Now, how can you
run such a simulation in the computer?
You can introduce
The Java library has a random number generator, which produces numbers that
randomness by appear to be completely random. Calling Math.random() yields a random floating-point
calling the random number that is ≥ 0 and < 1. Call Math.random() again, and you get a different number.
number generator.
The following program calls Math.random() ten times.

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.

4.9.2 Simulating Die Tosses


In actual applications, you need to transform the output from
the random num­ber generator into different ranges. For exam­
ple, to simulate the throw of a die, you need random integers
between 1 and 6.
Here is the general recipe for computing random integers
between two bounds a and b. As you know from Program­
ming Tip 4.3 on page 156, there are b - a + 1 values between a and
b, including the bounds themselves. First compute
(int) (Math.random() * (b ‑ a + 1))

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;

Here is a program that simulates the throw of a pair of dice:

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

4.9.3 The Monte Carlo Method


The Monte Carlo method is
an ingenious method for find-
ing approximate solutions to
problems that cannot be pre-
cisely solved. (The method is
named after the famous casino in
Monte Carlo.) Here is a typical
exam­ple. It is difficult to com-
pute the number p, but you can
approximate it quite well with
the following simulation.
Simulate shooting a dart into a square surrounding a circle of radius 1. That is easy:
generate random x and y coordinates between –1 and 1.
y
If the generated point lies inside the circle, we count
2 + y2 ≤ 1. Because our
it as a hit. That is the case when x 1
shots are entirely random, we expect that the ratio of hits
/ tries is approximately equal to the ratio of the areas of
the cir­cle and the square, that is, p / 4. Therefore, our x
estimate for p is 4 × hits / tries. This method yields an –1 1
estimate for p, using nothing but simple arithmetic.
To generate a random floating-point value between –1
–1
and 1, you compute:
double r = Math.random(); // 0 ≤ r < 1
double x = -1 + 2 * r; // –1 ≤ x < 1

As r ranges from 0 (inclusive) to 1 (exclusive), x ranges from –1 + 2 × 0 = –1 (inclusive)


to –1 + 2 × 1 = 1 (exclusive). In our application, it does not matter that x never reaches
1. The points that fulfill the equation x = 1 lie on a line with area 0.
Here is the program that carries out the simulation:

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

20 // Check whether the point lies in the unit circle


21
22 if (x * x + y * y <= 1) { hits++; }
23 }
24
25 /*
26 The ratio hits / tries is approximately the same as the ratio
27 circle area / square area = pi / 4
28 */
29
30 double piEstimate = 4.0 * hits / TRIES;
31 System.out.println("Estimate for pi: " + piEstimate);
32 }
33 }

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.

Special Topic 4.3 Drawing Graphical Shapes


In Java, it is easy to produce simple drawings such as the
one in Figure 8. By writing programs that draw such pat­
terns, you can practice programming loops. For now, we
give you a program outline into which you place your
drawing code. The program outline also contains the
necessary code for displaying a window containing your
drawing. You need not look at that code now. It will be
discussed in detail in Chapter 10.
Your drawing instructions go inside the draw method:
public class TwoRowsOfSquares
{
public static void draw(Graphics g)
{
Drawing instructions Figure 8 Two Rows of Squares
}
. . .
}
When the window is shown, the draw method is called, and your drawing instructions will be
executed.
180 Chapter 4 Loops

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.

Table 4 Graphics Methods


Method Result Notes

g.drawRect(x, y, width, height) (x, y) is the top left corner.

g.drawOval(x, y, width, height) (x, y) is the top left corner


of the box that bounds the
ellipse. To draw a circle, use
the same value for width
and height.
g.fillRect(x, y, width, height) The rectangle is filled in.

g.fillOval(x, y, width, height) The oval is filled in.

g.drawLine(x1, y1, x2, y2) (x1, y1) and (x2, y2) are
the endpoints.

g.drawString("Message", x, y) (x, y) is the basepoint.

Basepoint Baseline

g.setColor(color) From now on, Use Color.RED, Color.GREEN,


draw or fill methods Color.BLUE, and so on. (See
will use this color. Table 10.1 for a complete
list of predefined colors.)

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

11 public static void draw(Graphics g)


12 {
13 final int width = 20;
14 g.setColor(Color.BLUE);
15
16 // Top row. Note that the top left corner of the drawing has coordinates (0, 0)
17 int x = 0;
18 int y = 0;
19 for (int i = 0; i < 10; i++)
20 {
21 g.fillRect(x, y, width, width);
22 x = x + 2 * width;
23 }
24 // Second row, offset from the first one
25 x = width;
26 y = width;
27 for (int i = 0; i < 10; i++)
28 {
29 g.fillRect(x, y, width, width);
30 x = x + 2 * width;
31 }
32 }
33
34 public static void main(String[] args)
35 {
36 // Do not look at the code in the main method
37 // Your code will go into the draw method above
38
39 JFrame frame = new JFrame();
40
41 final int FRAME_WIDTH = 400;
42 final int FRAME_HEIGHT = 400;
43
44 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
45 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
46
47 JComponent component = new JComponent()
48 {
49 public void paintComponent(Graphics graph)
50 {
51 draw(graph);
52 }
53 };
54
55 frame.add(component);
56 frame.setVisible(true);
57 }
58 }

Video E xamp le 4.2 Drawing a Spiral


In this Video Example, you will see how to develop a program
that draws a spiral.

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


182 Chapter 4 Loops

.
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 hum­blest of programs. word processors in the local script or software. The same
Writing a real soft­ware 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 var­ious songs or movies
chance to make more money from their schemes to ensure that only the legiti- with­out payment. Or you may have
effort. (Actually, some companies give mate owner could use the soft­ware, 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 dif­fi 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 mea­sures. They paid for it can be dif­fi 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 inconve­niences, such as hav- publisher charges a lot of money for
there are individuals who donate their ing multiple don­gles 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­ bur­dening 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

Explain the flow of execution in a loop.

• A loop executes instructions repeatedly while a


condition is true.
• An off-by-one error is a common error when
programming loops. Think through simple test
cases to avoid this type of error.
Use the technique of hand-tracing to analyze the behavior of a pro­gram.

• Hand-tracing is a simulation of code execution in which you step


through instructions and track the values of the variables.
• Hand-tracing can help you understand how an unfamiliar algo­
rithm works.
• Hand-tracing can show errors in code or pseudocode.
Chapter Summary 183

Use for loops for implementing count-controlled loops.

• The for loop is used when a value runs from a starting point to an ending point
with a constant increment or decrement.

Choose between the while loop and the do loop.

• The do loop is appropriate when the loop body must be executed at least once.

Implement loops that read sequences of input data.

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

Use the technique of storyboarding for planning user interactions.

• A storyboard consists of annotated sketches for each step in an action sequence.


• Developing a storyboard helps you understand the inputs and outputs that are
required for a program.
Know the most common loop algorithms.

• To compute an average, keep a total and a count of all values.


• To count values that fulfill a condition, check all values and increment a counter
for each match.
• If your goal is to find a match, exit the loop when the match is found.
• To find the largest value, update the largest value seen so far whenever you see a
larger one.
• To compare adjacent inputs, store the preceding input in a variable.

Use nested loops to implement multiple levels of iteration.

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

Apply loops to the implementation of simulations.

• In a simulation, you use the computer to simulate an activity.


• You can introduce randomness by calling the random number
generator.
184 Chapter 4 Loops

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.1 Write a while loop that prints


a. All squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81.
b. All positive numbers that are divisible by 10 and less than n. For example, if n is
100, print 10 20 30 40 50 60 70 80 90
c. All powers of two less than n. For example, if n is 100, print 1 2 4 8 16 32 64.

•• R4.2 Write a loop that computes


a. The sum of all even numbers between 2 and 100 (inclusive).
b. The sum of all squares between 1 and 100 (inclusive).
c. The sum of all odd numbers between a and b (inclusive).
d. The sum of all odd digits of n. (For example, if n is 32677, the sum would
be 3 + 7 + 7 = 17.)
• R4.3 Provide trace tables for these loops.
a. int i = 0; int j = 10; int n = 0;
while (i < j) { i++; j--; n++; }
b. int i = 0; int j = 0; int n = 0;
while (i < 10) { i++; n = n + i + j; j++; }
c. int i = 10; int j = 0; int n = 0;
while (i > 0) { i--; j++; n = n + i - j; }
d. int i = 0; int j = 10; int n = 0;
while (i != j) { i = i + 2; j = j - 2; n++; }

• R4.4 What do these loops print?


a. for (int i = 1; i < 10; i++) { System.out.print(i + " "); }
b. for (int i = 1; i < 10; i += 2) { System.out.print(i + " "); }
c. for (int i = 10; i > 1; i--) { System.out.print(i + " "); }
d. for (int i = 0; i < 10; i++) { System.out.print(i + " "); }
e. for (int i = 1; i < 10; i = i * 2) { System.out.print(i + " "); }
f. for (int i = 1; i < 10; i++) { if (i % 2 == 0) { System.out.print(i + " "); } }

• 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 termi­nated
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

Provide a trace table for this sample input.


186 Chapter 4 Loops

• R4.15 Rewrite the following for loop into a while loop.


int s = 0;
for (int i = 1; i <= 10; i++)
{
s = s + i;
}

• R4.16 Rewrite the following do loop into a while loop.


int n = in.nextInt();
double x = 0;
double s;
do
{
s = 1.0 / (1 + n * n);
n++;
x = x + s;
}
while (s > 0.01);

• R4.17 Provide trace tables of the following loops.


a. int s = 1;
int n = 1;
while (s < 10) { s = s + n; }
n++;
b. int s = 1;
for (int n = 1; n < 5; n++) { s = s + n; }
c. int s = 1;
int n = 1;
do
{
s = s + n;
n++;
}
while (s < 10 * n);

• 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 sce­nario 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 story­board
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

•• R4.27 The nested loops


for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= width; j++) { System.out.print("*"); }
System.out.println();
}
display a rectangle of a given width and height, such as
****
****
****
Write a single for loop that displays the same rectangle.
•• R4.28 Suppose you design an educational game to teach children how to read a clock. How
do you generate random values for the hours and minutes?
••• R4.29 In a travel simulation, Harry will visit one of his friends that are located in three
states. He has ten friends in California, three in Nevada, and two in Utah. How do
you produce a random number between 1 and 3, denoting the destination state, with
a probability that is proportional to the number of friends in each state?

P r o g r a mmi n g E x e r ci s e s

• P4.1 Write programs with loops that compute


a. The sum of all even numbers between 2 and 100 (inclusive).
b. The sum of all squares between 1 and 100 (inclusive).
c. All powers of 2 from 20 up to 220.
d. The sum of all odd numbers between a and b (inclusive), where a and b are
inputs.
e. The sum of all odd digits of an input. (For example, if the input is 32677, the
sum would be 3 + 7 + 7 = 17.)
•• P4.2 Write programs that read a sequence of integer inputs and print
a. The smallest and largest of the inputs.
b. The number of even and odd inputs.
c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print
1 8 10 19.
d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 6 2, the
program should print 3 5 6.
•• P4.3 Write programs that read a line of input as a string and print
a. Only the uppercase letters in the string.
b. Every second letter of the string.
c. The string, with all vowels replaced by an underscore.
d. The number of vowels in the string.
e. The positions of all vowels in the string.

•• 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:

first i middle j last

Then replace the string with


first + word.charAt(j) + middle + word.charAt(i) + last

• 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 pro­vides 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.13 Write a program that prints all powers of 2 from 20 up to 220.

•• 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 aver­age, 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 individ­ual 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

•• P4.16 The Fibonacci numbers are defined by the sequence

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 pro­gram
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 win­ning 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, ran­domly 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 orig­inal 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

because the truncation of an overflowing result to the int type is equivalent to


computing the remainder.
Write a program that asks the user to enter a seed value for rold. (Such a value is often
called a seed). Then print the first 100 random integers generated by this formula,
using a = 32310901 and b = 1729.
•• P4.26 The Buffon Needle Experiment. The follow­ing experiment was devised by Comte
Georges-Louis Leclerc de Buffon (1707–1788), a French naturalist. A needle of
length 1 inch is dropped onto paper that is ruled with lines 2 inches apart. If the
needle drops onto a line, we count it as a hit. (See Figure 9.) Buffon discovered that
the quotient tries/hits approximates p.

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-coordi­nate 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

•• Business P4.27 Currency conversion. Write a program


that first asks the user to type today’s
price for one dollar in Japanese yen,
then reads U.S. dollar values and
converts each to yen. Use 0 as a sentinel.
•• Business P4.28 Write a program that first asks the user
to type in today’s price of one dollar
in Jap­anese yen, then reads U.S. dollar
values and converts each to Japanese
yen. Use 0 as the sentinel value to denote the end of dollar inputs. Then the program
reads a sequence of yen amounts and converts them to dollars. The second sequence
is ter­minated by another zero value.
•• Business P4.29 Your company has shares of stock it would like to sell when their value exceeds a
certain target price. Write a program that reads the target price and then reads the
current stock price until it is at least the target price. Your program should use a
Scanner to read a sequence of double values from standard input. Once the minimum
is reached, the program should report that the stock price exceeds the target price.
•• Business P4.30 Write an application to pre-sell a limited number of cinema tickets. Each buyer can
buy as many as 4 tickets. No more than 100 tickets can be sold. Implement a pro­
gram called TicketSeller that prompts the user for the desired number of tickets and
then displays the number of remaining tickets. Repeat until all tickets have been
sold, and then display the total number of buyers.
•• Business P4.31 You need to control the number of people who can be in an oyster bar at the same
time. Groups of people can always leave the bar, but a group cannot enter the bar
if they would make the number of people in the bar exceed the maximum of 100
occupants. Write a program that reads the sizes of the groups that arrive or depart.
Use negative numbers for departures. After each input, display the current number
of occupants. As soon as the bar holds the maximum number of people, report that
the bar is full and exit the program.
••• Business P4.32 Credit Card Number Check. The last digit of a credit card number is the check
digit, which protects against transcription errors such as an error in a single digit or
switching two digits. The following method is used to verify actual credit card num­
bers but, for simplicity, we will describe it for numbers with 8 digits instead of 16:
• Starting from the rightmost digit, form the sum of every other digit. For
example, if the credit card number is 4358 9795, then you form the sum
5 + 7 + 8 + 3 = 23.
• Double each of the digits that were not included in the preceding step. Add all
digits of the resulting numbers. For example, with the number given above,
doubling the digits, starting with the next-to-last one, yields 18 18 10 8. Adding
all digits in these values yields 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27.
• Add the sums of the two preceding steps. If the last digit of the result is 0, the
number is valid. In our case, 23 + 27 = 50, so the number is valid.
Write a program that implements this algorithm. The user should supply an 8-digit
number, and you should print out whether the number is valid or not. If it is not
valid, you should print the value of the check digit that would make it valid.
Programming Exercises 195

•• 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 peri­ods. 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 start­ing
velocity v0. Any calculus book will state that the position of the ball after t sec­onds is
s(t ) = − 1 gt 2 + v0t, where g = 9.81 m s2 is the gravi­tational 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 con­stant, 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 posi­tion only every full second. Also printout the
values from the exact formula s(t ) = − 1 gt 2 + v0t for com­parison.
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 mis­siles.
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.)

The cross-sectional area at a point x is called the “section” in nauti­


cal parlance. To compute it, let z go from 0 to –T in n increments,
each of size T n. For each value of z, compute the value for y.
Then sum the areas of trapezoidal strips. At right are the strips
where n = 4.
Write a program that reads in values for B, L, T, x, and n and then
prints out the cross-sectional area at x.
• Science P4.36 Radioactive decay of radioactive materials can be mod­
eled by the equation A = A0e-t (log 2̸h), where A is the
amount of the material at time t, A0 is the amount at
time 0, and h is the half-life.
Technetium-99 is a radioisotope that is used in imaging
of the brain. It has a half-life of 6 hours. Your program
should display the relative amount A ̸ A0 in a patient
body every hour for 24 hours after receiving a dose.
••• Science P4.37 The photo at left shows an electric device called a “transformer”. Transformers are
often constructed by wrapping coils of wire around a ferrite core. The figure below
illustrates a situation that occurs in various audio devices such as cell phones and
music players. In this circuit, a transformer is used to connect a speaker to the output
of an audio amplifier.
R0 = 20 Ω
1:n

+
– Vs = 40 V Rs = 8 Ω

Amplifier Transformer Speaker


Programming Exercises 197

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
com­pute 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

1. 23 years. This yields the correct answer. The number


2. 7 years. 123 has 3 digits.
3. Add a statement count temp
1 100
System.out.println(balance);
2 10.0
as the last statement in the while loop.
This yields the wrong answer. The number 100
4. The program prints the same output. This is also has 3 digits. The loop condition should
because the balance after 14 years is slightly have been
below $20,000, and after 15 years, it is slightly
above $20,000. while (temp >= 10)
5. 2 4 8 16 32 64 128 11. int year = 1;
while (year <= nyears)
Note that the value 128 is printed even though {
it is larger than 100. double interest = balance * RATE / 100;
balance = balance + interest;
6. n output System.out.printf("%4d %10.2f\n",
5 year, balance);
4 4 year++;
3 3 }
2 2
1 1 12. 11 numbers: 10 9 8 7 6 5 4 3 2 1 0
0 0 13. for (int i = 10; i <= 20; i = i + 2)
-1 -1 {
7. n output System.out.println(i);
1 1, }
2 1, 2, 14. int sum = 0;
3 1, 2, 3, for (int i = 1; i <= n; i++)
4 {
There is a comma after the last value. Usually, sum = sum + i;
commas are between values only. }

8. a n r i 15. for (int year = 1;


2 4 1 1 balance <= 2 * INITIAL_BALANCE; year++)
2 2
However, it is best not to use a for loop in this
4 3
8 4 case because the loop condition does not relate
16 5 to the year variable. A while loop would be a
The code computes an. better choice.
16. do
9. n output
{
1 1
System.out.print(
11 11
"Enter a value between 0 and 100: ");
21 21
value = in.nextInt();
31 31
}
41 41
while (value < 0 || value > 100);
51 51
61 61 17. int value = 100;
... while (value >= 100)
{
This is an infinite loop. n is never equal to 50. System.out.print("Enter a value < 100: ");
10. count temp value = in.nextInt();
1 123 }
2 12.3
3 1.23
Answers to Self-Check Questions 199

Here, the variable value had to be initialized 27. Simple conversion


with an artificial value to ensure that the loop Only one value can be converted
is entered at least once. Your conversion question: How many in are 30 cm
18. Yes. The do loop 30 cm = 11.81 in
Run program again for another question
(Program exits)
do { body } while (condition);
is equivalent to this while loop: Unknown unit
boolean first = true;
while (first || condition) Your conversion question: How many inches are 30 cm?
{ Unknown unit: inches
body; Known units are in, ft, mi, mm, cm, m, km, oz, lb, g, kg, tsp, tbsp, pint, gal
(Program exits)
first = false;
}
Program doesn’t understand question syntax
19. int x;
int sum = 0;
Your conversion question: What is an ångström?
do Please formulate your question as “How many (unit) are (value) (unit)?”
{ (Program exits)
x = in.nextInt();
sum = sum + x; 28. One score is not enough
}
while (x != 0);
Enter scores, Q to quit: 90 Q
20. int x = 0; Error: At least two scores are required.
int previous; (Program exits)
do
{ 29. It would not be possible to implement this
previous = x; interface using the Java features we have cov­
x = in.nextInt(); ered up to this point. There is no way for the
sum = sum + x;
}
program to know when the first set of inputs
while (x != 0 && previous != x); ends. (When you read numbers with value =
in.nextDouble(), it is your choice whether to put
21. No data
them on a single line or multiple lines.)
22. The first check ends the loop after the sentinel
30. Comparing two inter­est rates
has been read. The second check ensures that
the sentinel is not processed as an input value. First interest rate in percent: 5
23. The while loop would never be entered. The Second interest rate in percent: 10
Years: 5
user would never be prompted for input. Year 5% 10%
Because count stays 0, the program would then
This row clarifies that 1 means
print "No data". 0 10000.00 10000.00
the end of the first year
1 10500.00 11000.00
24. The nextDouble method also returns false. 2 11025.00 12100.00
A more accurate prompt would have been: 3 11576.25 13310.00
4 12155.06 14641.00
“Enter values, a key other than a digit to quit.” 5 12762.82 16105.10
But that might be more con­fusing to the pro­
gram user who would need now ponder which
31. The total is zero.
key to choose.
32. double total = 0;
25. If the user doesn’t provide any numeric input, while (in.hasNextDouble())
the first call to in.nextDouble() will fail. {
26. Computing the aver­age double input = in.nextDouble();
if (input > 0) { total = total + input; }
}
Enter scores, Q to quit: 90 80 90 100 80 Q
The average is 88 33. position is str.length() and ch is unchanged
(Program exits) from its initial value, '?'. Note that ch must
200 Chapter 4 Loops

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 proba­bility.
if (first) { first = false; } When throwing a pair of dice, the number 7 is
else if (input == previous) six times as likely as the num­ber 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.

You might also like