Chapter 6

Iteration


Chapter Goals

while Loops

Calculating the Growth of an Investment

Calculating the Growth of an Investment

File Investment.java

File InvestmentTester.java


Output

   The investment doubled after 15 years

while Loop Flowchart



Syntax 7.1: The while Statement

  while (condition)
   statement

Example:

 
while (balance < targetBalance)
{
year++;
double interest = balance * rate / 100;
balance = balance + interest;
}

Purpose:

To repeatedly execute a statement as long as a condition is true

Self Check

  1. How often is the statement in the loop
    while (false) statement;
    executed?
  2. What would happen if RATE was set to 0 in the main method of the InvestmentTester program?

Answers

  1. Never
  2. The waitForBalance method would never return due to an infinite loop

Common Error: Infinite Loops

Common Error: Off-by-One Errors

Avoiding Off-by-One Error


do Loops

do Loop Flowchart


Spaghetti Code


for Loops

Flowchart for for Loop


Syntax 7.2: The for Statement

  for (initialization; condition; update)
   statement

Example:

  for (int i = 1; i <= n; i++)
{
   double interest = balance * rate / 100;
   balance = balance + interest;
}

Purpose:

To execute an initialization, then keep executing a statement and updating an expression while a condition is true

File Investment.java

File InvestmentTester.java


Output

   The balance after 20 years is 26532.98

Self Check

  1. Rewrite the for loop in the waitYears method as a while loop
  2. How many times does the following for loop execute?
    for (i = 0; i <= 10; i++)
    System.out.println(i * i);

Answers

  1. int i = 1;
    while (i <= n)
    {
    double interest = balance * rate / 100;
    balance = balance + interest;
    i++;
    }
  2. 11 times

Common Errors: Semicolons

Nested Loops

File Triangle.java

File TriangleTester.java

Output

   []
[][]
[][][]

[]
[][]
[][][]
[][][][]
[][][][][]
[][][][][][]
[][][][][][][]
[][][][][][][][]
[][][][][][][][][]
[][][][][][][][][][]
[][][][][][][][][][][]
[][][][][][][][][][][][]
[][][][][][][][][][][][][]
[][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][]

Self Check

  1. How would you modify the nested loops so that you print a square instead of a triangle?
  2. What is the value of n after the following nested loops?
    int n = 0;
    for (int i = 1; i <= 5; i++)
    for (int j = 0; j < i; j++)
    n = n + j;

Answers

  1. Change the inner loop to for (int j = 1; j <= width; j++)
  2. 20

Processing Sentinel Values

Loop and a half

File InputTester.java

File DataSet.java


Output

   Enter value, Q to quit: 10
   Enter value, Q to quit: 0
   Enter value, Q to quit: -1
   Enter value, Q to quit: Q
   Average = 3.0
   Maximum = 10.0

Self Check

  1. Why does the InputTester class call in.next and not in.nextDouble?
  2. Would the DataSet class still compute the correct maximum if you simplified the update of the maximum field in the add method to the following statement?
    if (maximum < x) maximum = x;

Answers

  1. Because we don't know whether the next input is a number or the letter Q.
  2. No. If all input values are negative, the maximum is also negative. However, the maximum field is initialized with 0. With this simplification, the maximum would be falsely computed as 0.

Random Numbers and Simulations


File Die.java

File DieTester.java


Output

   6 5 6 3 2 6 3 4 4 1

Second Run
   3 2 2 1 6 5 3 4 1 2

Buffon Needle Experiment


Needle Position



Needle Position

File Needle.java

File NeedleTester.java


Output

   Tries = 10000, Tries / Hits = 3.08928
Tries = 1000000, Tries / Hits = 3.14204

Self Check

  1. How do you use a random number generator to simulate the toss of a coin?
  2. Why is the NeedleTester program not an efficient method for computing π?

Answers

  1. int n = generator.nextInt(2); // 0 = heads, 1 = tails
  2. The program repeatedly calls Math.toRadians(angle). You could simply call Math.toRadians(180) to compute π