Chapter 6 Iteration Goals To be able to
Chapter 6 Iteration Goals • To be able to program loops with the while , for , and do statements • To avoid infinite loops and off-by-one errors • To understand nested loops • To learn how to process input • To implement simulations
Investment with Compound Interest Invest $10, 000, 5% interest, compounded annually 1. When will the balance be at least $20, 000? 2. What is the new balance after 5 years?
Syntax 6. 1. The while Statement • Syntax while (condition) statement repeats the statement while the condition is true • Example: while (balance < target. Balance) { year++; double interest = balance * rate / 100; balance = balance + interest; } • Purpose: To execute a statement while a condition is true
Flowchart for while Loop
Investment. java 25 public void wait. For. Balance(double target. Balance) 26 { 1 /** 27 while (balance < target. Balance) 2 A class to monitor the growth of an 28 { years++; 3 investment that accumulates interest at a 29 fixed annual rate 30 double interest = balance * rate / 100; 31 balance = balance + interest; 4 */ 32 } 5 public class Investment 33 } 6{ 35 /** 7 /** 8 Constructs an Investment object from a 36 Gets the current investment balance. 37 @return the current balance 9 starting balance and interest rate. 10 @param a. Balance the starting balanece 38 */ 11 @param a. Rate the interest rate in percent 39 public double get. Balance() 40 { return balance; } 12 */ 44 /** 13 public Investment(double a. Balance, 45 Gets the number of years this investment double a. Rate) 46 has accumulated interest. 14 { 47 @return the number of years since the 15 balance = a. Balance; 48 start of the investment 16 rate = a. Rate; 48 */ 17 years = 0; 49 public int get. Years() 18 } 50 { 20 /** 51 return years; 52 } 21 Keeps accumulating interest until a target balance has been reached. 54 private double balance; 55 private double rate; 23 @param target. Balance the desired 56 private int years; balance 57 } 24 */
Investment. Test. java 10 final double RATE = 5; 1/** 11 Investment invest = new 2 This program computes how Investment(INITIAL_BAL long it takes for an investment ANCE, RATE); 3 to double. 12 invest. wait. For. Balance(2 * 4 */ INITIAL_BALANCE); 5 public class Investment. Test 13 int years = invest. get. Years(); 6{ 14 System. out. println("The 7 public static void main(String[] investment doubled after " args) 15 + years + " years"); 8{ 16 } 9 final double 17 } INITIAL_BALANCE = 10000;
Common Errors with while statement • Infinite Loop – while (year < 20) { balance = balance + balance * rate / 100; · Off-by-1 Error – year = 0; while (balance < target. Balance) { year++; } double interest=balance*rate/100; while (year > 0) balance = balance + interest; { } year++; // oops, -System. out. println("Reached target } after “ + year + " years. "); – Loops run forever--must - Should year start at 0 or 1? kill program - Should the test be < or <=? - interest rate 100% · Avoiding Off-by-1 Error after one year: - Run through a simple example: balance = $20, 000 target balance = $20, 000, interest loop should stop rate 50% Therefore: must use < after one year: balance = $15, 000 after two years: balance = $22, 500 - Think, don't compile and try at random Therefore: year must start at 0
do Statement • • Syntax: do statement while (condition); • Purpose: Executes loop body at least once Flowchart for do Loop Example: Validate input double value; do { String input =JOption. Pane. show. Input. Dialog ("Please enter a positive number"); value =Integer. parse. Int(input); } while (input <= 0);
Syntax 6. 2. The for Statement · Syntax: for (initialization; condition; update) statement Flowchart for Loop · Example: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance+interest; } · Equivalent to initialization; while (condition) { statement; update; } • Purpose: To execute an initialization, then keep executing a statement and updating an expression while a condition is true
Investment. java 1 /** 2 A class to monitor the growth of an investment that 3 accumulates interest at a fixed annual rate 4 */ 5 public class Investment 6{ 7 /** 8 Constructs an Investment object from a starting balance and 9 interest rate. 10 @param a. Balance the starting balanece 11 @param a. Rate the interest rate in percent 12 */ 13 public Investment(double a. Balance, double a. Rate) 14 { 15 balance = a. Balance; 16 rate = a. Rate; 17 years = 0; 18 } 19 20 /** 21 Keeps accumulating interest until a target balance has 22 been reached. 23 @param target. Balance the desired balance 24 */ 25 public void wait. For. Balance(double target. Balance) 26 { 27 while (balance < target. Balance) 28 { 29 years++; 30 double interest = balance * rate / 100; 31 balance = balance + interest; 32 } 33 }
35 /** 36 Keeps accumulating interest for a given number of years. 53 public double get. Balance() 54 { 37 @param n the number of years 55 return balance; 38 */ 56 } 39 public void wait. Years(int n) 58 /** 40 { 59 Gets the number of years this investment has accumulated interest. 41 for (int i = 1; i <= n; i++) 42 { 43 double interest = balance * rate / 100; 44 balance = balance + interest; 45 } 46 years = years + n; 47 } 49 /** 50 Gets the current investment balance. 51 @return the current balance 52 */ 61 @return the number of years since the start of the investment 62 */ 63 public int get. Years() 64 { 65 return years; 66 } 68 private double balance; 69 private double rate; 70 private int years; 71 }
Investment. Test. java 1 /** 2 This program computes how much an investment grows in 3 a given number of years. 4 */ 5 public class Investment. Test 6{ 7 public static void main(String[] args) 8{ 9 final double INITIAL_BALANCE = 10000; 10 final double RATE = 5; 11 final int YEARS = 20; 12 Investment invest = new Investment(INITIAL_BALAN CE, RATE); 13 invest. wait. Years(YEARS); 14 double balance = invest. get. Balance(); 15 System. out. println("The balance after " + YEARS + 16 " years is " + balance); 17 } 18 }
Common Errors: Semicolons • A semicolon that shouldn't be there sum = 0; for (i = 1; i <= 10; i++) ; sum = sum + i; System. out. println(sum); // A missing semicolon for (i = 1; i <= 10; sum = sum + i++) System. out. println(sum);
Nested Loops · Create triangle pattern · Make triangle row is [] [][][] · Loop through rows another loop for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "n"; · Put loops together => for (int i = 1; i <= n; i++) Nested loops { // make triangle row }
Triangle. java 1 /** 2 This class describes triangle objects that can be displayed as shapes like this: 4 [] 5 [][] 6 [][][] 7 */ 8 public class Triangle 9{ 10 /** 11 Constructs a triangle. 12 @param a. Width the number of [] in the last row of the triangle. 13 */ 14 public Triangle(int a. Width) 15 { 16 width = a. Width; 17 } 18 19 /** 20 Computes a string representing the triangle. 21 @return a string consisting of [] and newline characters 22 */ 23 public String to. String() 24 { 25 String r = ""; 26 for (int i = 1; i <= width; i++) 27 { 28 // make triangle row 29 for (int j = 1; j <= i; j++) 30 r = r + "[]"; 31 r = r + "n"; 32 } 33 return r; 34 } 35 36 private int width; 37 }
Triangle. Test. java 1 /** 2 This program tests the Triangle class. 3 */ 4 public class Triangle. Test 5 { 6 public static void main(String[] args) 7 { 8 Triangle small = new Triangle(3); 9 System. out. println(small. to. String()); 10 11 Triangle large = new Triangle(15); 12 System. out. println(large. to. String()); 13 } 14 }
Reading Input Values • General pattern: boolean done = false; while (!done) { String input = read input; if (end of input indicated) done = true; else { // process input } } • "Loop and a half”: The true test for loop termination is in the middle of the loop, not at the top
Data. Set. java 1 /** 2 Computes the average of a set of data values. 3 */ 4 public class Data. Set 5{ 6 /** 7 Constructs an empty data set. 8 */ 9 public Data. Set() 10 { 11 sum = 0; 12 count = 0; 13 maximum = 0; 14 } 15 16 /** 17 Adds a data value to the data set 18 @param x a data value 19 */ 20 public void add(double x) 21 { 22 sum = sum + x; 26 23 if (count == 0 || maximum < x) maximum = x; 24 count++; 25 } 27 /** 28 Gets the average of the added data. 29 @return the average or 0 if no data has been added 30 */ 31 public double get. Average() 32 { 33 if (count == 0) return 0; 34 else return sum / count; 35 } 37 /** 38 Gets the largest of the added data. 39 @return the maximum or 0 if no data has been added 40 */ 41 public double get. Maximum() 42 { 43 return maximum; 44 } 46 private double sum; 47 private double maximum; 48 private int count; 49 }
Input. Test. java 1 import javax. swing. JOption. Pane; 3 /** 4 This program computes the average and maximum of a set 5 of input values. 6 */ 7 public class Input. Test 8{ 9 public static void main(String[] args) 10 { 11 Data. Set data = new Data. Set(); 12 13 boolean done = false; 14 while (!done) 15 { 16 String input = JOption. Pane. show. Input. Dialog( "Enter value, Cancel to quit"); 17 if (input == null) 18 done = true; 19 else 20 { 21 double x = Double. parse. Double(input); 22 data. add(x); 23 } 24 } 25 26 System. out. println("Average = " + data. get. Average()); 27 System. out. println("Maximum = " + data. get. Maximum()); 28 } 29 }
String Tokenization · String. Tokenizer breaks up string into tokens · By default, white space separates tokens · "4. 3 7 -2" breaks into three tokens: "4. 3", "7", "-2" • String. Tokenizer tokenizer = new String. Tokenizer(); while (tokenizer. has. More. Tokens()) { String token = tokenizer. next. Token(); // process token }
Input. Test. java 1 import java. util. String. Tokenizer; 2 import javax. swing. JOption. Pane; 3 4 /** 5 This program computes the average and maximum of a set 6 of input values that are entered on a single line. 7 */ 8 public class Input. Test 9{ 10 public static void main(String[] args) 11 { 12 Data. Set data = new Data. Set(); 13 14 String input = JOption. Pane. show. Input. Dialog( "Enter values: "); 15 String. Tokenizer tokenizer = new String. Tokenizer(input); 16 while (tokenizer. has. More. Tokens()) 17 { 18 String token = tokenizer. next. Token(); 19 double x = Double. parse. Double(token); 21 data. add(x); 22 } 23 24 System. out. println("Average = " + data. get. Average()); 25 System. out. println("Maximum = " + data. get. Maximum()); 26 } 27 }
Traversing Characters in String · s. char. At(i) is the ith character of the string s int vowel. Count = 0; String vowels = "aeiouy"; for (int i = 0; i < s. length(); i++) { char ch = s. char. At(i); if (vowels. index. Of(ch) >= 0) · Example: Count vowels vowel. Count++; · s. index. Of(ch) is the } index of the first occurrence of ch in s, or 1 if ch doesn't occur in s – for (int i = 0; i < s. length(); i++) { char ch = s. char. At(i); process ch }
Random Numbers · Random number generator Random generator = new Random(); int n = generator. next. Int(a); // 0 <= n < a double x = generator. next. Double(); // 0 <= x < 1 · Throw die (random number between 1 and 6) int d = 1 + generator. next. Int(6);
Die. java 1 import java. util. Random; 2 3 /** 4 This class models a die that, when cast, lands on a random 5 face. 6 */ 7 public class Die 8{ 9 /** 10 Constructs a die with a given number of sides 11 @param s the number of sides, e. g. 6 for a normal die 12 */ 13 public Die(int s) 14 { 15 sides = s; 16 generator = new Random(); 17 } 18 19 /** 20 Simulates a throw of the die 21 @return the face of the die 22 */ 23 public int cast() 24 { 25 return 1 + generator. next. Int(sides); 26 } 27 28 29 private Random generator; 30 private int sides; 31 }
Die. Test. java 1 /** 2 This program simulates casting a die ten times. 3 */ 4 public class Die. Test 5 { 6 public static void main(String[] args) 7 { 8 Die d = new Die(6); 9 final int TRIES = 10; 10 for (int i = 1; i <= TRIES; i++) 11 { 12 int n = d. cast(); 13 System. out. print(n + " "); 14 } 15 System. out. println(); 16 } 17 }
Buffon Needle Experiment • Simulating of random events • On each try, a needle, of length 1 is dropped onto a paper ruled with lines of length 2 • If needles drops onto a line, hit • Conjecture: ties/hits π Needle Position · Needle length = 1, distance between lines = 2 · Generate random ylow between 0 and 2 · Generate random angle a between 0 and 180 degrees · yhigh = ylow + sin( a) · Hit if yhigh >= 2
Needle. java 1 import java. util. Random; 3 /** 4 This class simulates a needle in the Buffon needle experiment. 5 */ 6 public class Needle 7{ 8 /** 9 Constructs a needle. 10 */ 11 public Needle() 12 { 13 hits = 0; 14 generator = new Random(); 15 } 17 /** 18 Drops the needle on the grid of lines and remembers whether the needle hit a line. 20 */ 21 public void drop() 22 { 23 double ylow = 2 * generator. next. Double(); 24 double angle = 180 * generator. next. Double(); 26 // compute high point of needle 28 double yhigh = ylow + Math. sin(Math. to. Radians(angle)); 29 if (yhigh >= 2) hits++; 30 tries++; 31 } 33 /** 34 Gets the number of times the needle hit a line. 35 @return the hit count 36 */ 37 public int get. Hits() 38 { return hits; } 42 /** 43 Gets the total number of times the needle was dropped. 44 @return the try count 45 */ 46 public int get. Tries() 47 { return tries; } 51 private Random generator; 52 private int hits; 53 private int tries; 54 }
Needle. Test. java 1 /** 2 This program simulates the Buffon needle experiment and prints the resulting approximations of pi. 4 */ 5 public class Needle. Test 6{ 7 public static void main(String[] args) 8{ 9 Needle n = new Needle(); 10 final int TRIES 1 = 10000; 11 final int TRIES 2 = 100000; 12 13 for (int i = 1; i <= TRIES 1; i++) 14 n. drop(); 15 System. out. println("Tries / Hits = " + (double)n. get. Tries() / n. get. Hits()); 17 18 for (int i = TRIES 1 + 1; i <= TRIES 2; i++) 19 n. drop(); 20 System. out. println("Tries / Hits = " + (double)n. get. Tries() / n. get. Hits()); 22 } 23 }
- Slides: 28