Big Java 5

Chapter 6 – Iteration

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

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

Question Mar 13

What does the following loop print?
     int n = 1;
     while (n < 100)
     {
         n = 2 * n;
         System.out.print(n + " ");
     }
  1. 2 4 8 16 32 64
  2. 1 2 4 8 16 32 64 128
  3. 2 4 8 16 32 64 128
  4. Nothing. There is a syntax error
  5.  

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

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

Qestion 2 Mar 13

How many numbers does this loop print?
for (int n = 10; n >= 0; n--)
{
   System.out.println(n);
}
  1. 10 numbers
  2. 11 numbers
  3. 12 numbers
  4. Nothing. n does not exist inside the loop

Question 1 Mar 18

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

Two flavors of infinite loops

       //print the numbers from 5 to 1 (inclusive)
       for (int i = 5; i > 0; i++)
       {
          System.out.print(i + " ");
       }
  

The code above is not actually an infinite loop because of integer overflow and twos comlement arithmetic
The one below is

        //print the numbers from 5 to 1 (inclusive)
        int i =  1;
        while ( i > 0)
        {
            System.out.println(i );
        }
        //find sum of numbers from 1 to 10 (inclusive of both ends)
        int sum = 0;
        int i =  1;
        while ( i <= 10)
        {
            sum = sum + i;
        }

The Do Loop

Question 2 Mar 18

Suppose that we want to check for inputs that are at least 0 and at most 100. What should you use as the while loop condition

int value;
do
{
   System.out.print("Enter an integer < 100: ");
   value = in.nextInt();
}
while (...);
  1. while (value <= 0 && value >= 100);
  2. while (value <= 0 || value >= 100);
  3. while (value < 0 || value > 100);
  4. while (value < 0 && value >100);
  5. Something else

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?

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?

Question 3 Mar 18

In the example below, we use Q as the sentinal value" What happens when the user enters a X?

System.out.print("Enter values, Q to quit: ");
while (in.hasNextDouble())
{
   value = in.nextDouble();
   Process value.
}
  1. An InputMismatchException will be thrown
  2. The program will continue to prompt the user until he/whe enters a valid value
  3. The program will terminate
  4. An infinite loop results

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:

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?

Question 1 Mar 20

Write code to compute the total of all positive inputs?

  1. Got it!
  2. Worked on it but did not get the correct code
  3. Did not attempt

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?

Question 1 Apr 3

Write the code to find the position of the last space in a string? Don't use lastIndexOf

  1. Got it!
  2. Worked on it but did not get the correct code
  3. Did not attempt

Nested Loops

Nested Loop

flowchart of a nested loop

section_8/PowerTable.java

Your browser does not support this feature Program Run:

Question 2 Apr 3

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();
}
  1. 012
    123
    234
    345
  2. 0123
    1234
    2345
  3. 1234
    2345
    3456
  4. Something else

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

Question 3 Apr 3

Write code to produce this pattern

  ****
  ***
  **
  *
  1. Got it!
  2. Worked on it but did not get the correct code
  3. Did not attempt

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?