Big Java 5

Chapter 6 – Loops

Chapter Goals

loop-de-loop ride

The while Loop

The while Loop

The while Loop

Because the interest earned also earns interest, a bank balance grows exponentially.

coins

The while Loop

accelerator

The while Loop

The while Loop

The while Loop

Figure 1 Flowchart of a while Loop

flowchart for calculating interest

Syntax 6.1 The while Statement

syntax of a while loop

The while Loop

 

Execution of a while Loop

Execution of a while Loop

Figure 2 Execution of the Investment loop

Section_1/Investment.java

Your browser does not support the <object> tag.

Section_1/InvestmentRunner.java

Your browser does not support the <object> tag. Program Run:

Self Check 6.1

How many years does it take for the investment to triple? Modify the program and run it.

Self Check 6.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.

Self Check 6.3

Modify the program so that the balance after each year is printed. How did you do that?

Self Check 6.4

Suppose we change the program so that the condition of the while loop is

      while (balance <= targetBalance)

What is the effect on the program? Why?

Self Check 6.5

What does the following loop print?
     int n = 1;
     while (n < 100)
     {
         n = 2 * n;
         System.out.print(n + " ");
     }

while Loop Examples

while examples

Common Error: Infinite Loops

Common Error: Off-by-One Errors

Avoiding Off-by-One Error

Problem Solving: Hand-Tracing

Problem Solving: Hand-Tracing - Step by Step

Problem Solving: Hand-Tracing

Problem Solving: Hand-Tracing

Problem Solving: Hand-Tracing

Self Check 6.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);
}

Self Check 6.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++;
}

Self Check 6.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++;
}

Self Check 6.9

Trace the following code. What error do you observe?
int n = 1;
while (n != 50)
{
   System.out.println(n);
   n = n + 10;
}

Self Check 6.10

The following pseudo-code 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?

The for Loop

Syntax 6.2 for Statement

Santax for the for loop

The for Loop

for loop execution

Figure 3 Execution of a for Loop

The for Loop

The for Loop

The for Loop

The for Loop

The for Loop - Flowchart

flowchart of a for loop
Figure 4 Flowchart of a for loop

section_3/Investment.java

Your browser does not support the <object> tag.

section_3/InvestmentRunner.java

Your browser does not support the <object> tag. Program Run:

The for Loop Examples

for loop examples

Self Check 6.11

Write the for loop of the Investment class as a while loop.

Self Check 6.12

How many numbers does this loop print?
for (int n = 10; n >= 0; n--)
{
   System.out.println(n);
}

Self Check 6.13

Write a for loop that prints all even numbers between 10 and 20 (inclusive).

Self Check 6.14

Write a for loop that computes the sum of the integers from 1 to n.

Self Check 6.15

How would you modify the InvestmentRunner.java program to print the balances
after 20, 40, ..., 100 years?

The Do Loop

Self Check 6.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.

int value;
do
{
   System.out.print("Enter an integer < 100: ");
   value = in.nextInt();
}
while (value >= 100);

Self Check 6.17

Rewrite the input check do loop using a while loop. What is the disadvantage of your solution?

int value;
do
{
   System.out.print("Enter an integer < 100: ");
   value = in.nextInt();
}
while (value >= 100);

Self Check 6.18

Suppose Java didn't have a do loop. Could you rewrite any do loop as a while loop?

Self Check 6.19

Write a do loop that reads integers and computes their sum. Stop when reading the value 0.

Self Check 6.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.

Application: Processing Sentinel Values

 

Application: Processing Sentinel Values

section_5/SentinelDemo.java

Your browser does not support this feature Program Run:

Application: Processing Sentinel Values

Application: Processing Sentinel Values

Self Check 6.21

What does the SentinelDemo.java program print when the user immediately types -1 when prompted for a value?

Self Check 6.22

Why does the SentinelDemo.java program have two checks of the form salary != -1

Self Check 6.23

What would happen if the declaration of the salary variable in SentinelDemo.java was changed to

double salary = -1;

Self Check 6.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?

Self Check 6.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());

The "Loop and a Half" Problem

Sometimes termination condition of a loop can only be evaluated in the middle of the loop. There are different approaches:

The "Loop and a Half" Problem - Continued

Additional approaches:

Problem Solving: Storyboards

Problem Solving: Storyboards

Storyboarding for a problem to convert units of measurement.

Problem Solving: Storyboards - continued

Storyboarding for a problem to convert units of measurement - part 2.

Self Check 6.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.

Self Check 6.27

Google has a simple interface for converting units. You just type the question, and you get the answer. google

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.

Self Check 6.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.

Self Check 6.29

What is the problem with implementing the following storyboard in Java?

self check 6.29 question

Self Check 6.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.

Common Loop Algorithm: Sum and Average

Common Loop Algorithm: Counting Matches

Common Loop Algorithm: Counting Matches - Continued

Common Loop Algorithm: Finding the First Match

Common Loop Algorithm: Prompting Until a Match is Found

Common Loop Algorithm: Maximum and Minimum

Common Loop Algorithm: Maximum and Minimum

bus riders

To find the height of the tallest bus rider, remember the largest value so far, and update it whenever you see a taller one.

Common Loop Algorithm: Comparing Adjacent Values

Self Check 6.31

What total is computed when no user input is provided in the algorithm in Section 6.7.1?

Self Check 6.32

How do you compute the total of all positive inputs?

Self Check 6.33

What are the values of position and ch when no match is found in the algorithm in Section 6.7.3?

Self Check 6.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++)
{
   char ch = str.charAt(position);
   if (ch == ' ') { found = true; }
}

Self Check 6.35

How do you find the position of the last space in a string?

Self Check 6.36

What happens with the algorithm in Section 6.7.6 when no input is provided at all? How can you overcome that problem?

Nested Loops

Nested Loop

flowchart of a nested loop

section_8/PowerTable.java

Your browser does not support this feature Program Run:

Self Check 6.37

Why is there a statement System.out.println(); in the outer loop but not in the
inner loop?

Self Check 6.38

How would you change the program to display all powers from x0 to x5?

Self Check 6.39

If you make the change in Self Check 38, how many values are displayed?

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

Self Check 6.41

Write nested loops that make the following pattern of brackets:
[][][][]
[][][][]
[][][][]

Nested Loop Examples

Nested Loop Examples

Nested Loop Examples - Continued

Nested Loop Examples, continued

Application: Random Numbers and Simulations

Application: Random Numbers and Simulations

section_9_1/Die.java

Your browser does not support this feature

section_9_1/DieSimulator.java

Your browser does not support this feature Program Run:

The Monte Carlo Method

Using a simulation to calculate π

section_9_2/MonteCarlo.java

Your browser does not support this feature Program Run:

Self Check 6.42

How do you simulate a coin toss with the Random class?

Self Check 6.43

How do you simulate the picking of a random playing card?

Self Check 6.44

How would you modify the DieSimulator program to simulate tossing a pair of dice?

Self Check 6.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 = 2 + generator.nextInt(11);

Self Check 6.46

How do you generate a random floating-point number >= 0 and < 100?

Using a Debugger

The Debugger Stopping at a Breakpoint

Figure 7 - Stopping at a Breakpoint

Figure 8
Stopping at a Breakpoint

Inspecting Variables

Figure 9 - Inspecting Variables
Figure 9 Inspecting Variables

 

Debugging

Single-step Example

Self Check 6.47

In the debugger, you are reaching a call to System.out.println. Should you step into the method or step over it?

Self Check 6.48

In the debugger, you are reaching the beginning of a long method with a couple of loops inside. You want to find out the return value that is computed at the end of the method. Should you set a breakpoint, or should you step through the method?

Self Check 6.49

When using the debugger, you find that a variable has an unexpected value. How
can you go backwards to see when the variable changed?

Self Check 6.50

When using a debugger, should you insert statements to print the values of variables?

Self Check 6.51

Instead of using a debugger, could you simply trace a program by hand?