1 / 75

Chapter 6

Chapter 6. Iteration. Chapter 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.

yadid
Download Presentation

Chapter 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6 Iteration

  2. Chapter 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

  3. Investment with Compound Interest Invest $10,000, 5% interest, compounded annually When will the balance be at least $20,000?

  4. while Statement while (condition)statement;repeats the statement while the condition is truewhile (balance < targetBalance){year++;double interest = balance * rate / 100;balance = balance + interest;}

  5. File 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

  6. 9 interest rate. 10 @param aBalance the starting balanece 11 @param aRate the interest rate in percent 12 */ 13 public Investment(double aBalance, double aRate) 14 { 15 balance = aBalance; 16 rate = aRate; 17 years = 0; 18 } 19

  7. 20 /** 21 Keeps accumulating interest until a target balance has 22 been reached. 23 @param targetBalance the desired balance 24 */ 25 public void waitForBalance(double targetBalance) 26 { 27 while (balance < targetBalance)

  8. 28 { 29 years++; 30 double interest = balance * rate / 100; 31 balance = balance + interest; 32 } 33 } 34 35 /** 36 Gets the current investment balance. 37 @return the current balance 38 */

  9. 39 public double getBalance() 40 { 41 return balance; 42 } 43 44 /** 45 Gets the number of years this investment has accumulated 46 interest.

  10. 47 @return the number of years since the start of the investment 48 */ 49 public int getYears() 50 { 51 return years; 52 } 53 54 private double balance; 55 private double rate; 56 private int years; 57 }

  11. File InvestmentTest.java 1/** 2 This program computes how long it takes for an investment 3 to double. 4 */ 5 public class InvestmentTest 6 { 7 public static void main(String[] args) 8 {

  12. 9 final double INITIAL_BALANCE = 10000; 10 final double RATE = 5; 11 Investment invest = new Investment(INITIAL_BALANCE, RATE); 12 invest.waitForBalance(2 * INITIAL_BALANCE); 13 int years = invest.getYears(); 14 System.out.println("The investment doubled after " 15 + years + " years"); 16 } 17 }

  13. Flowchart for while Loop

  14. Syntax 6.1. The while Statement • while (condition)statementExample: • while (balance < targetBalance) • { • year++; • double interest = balance * rate / 100; • balance = balance + interest; • } • Purpose: • To execute a statement while a condition is true

  15. Common Error: Infinite Loop while (year < 20) { balance = balance + balance * rate / 100; } while (year > 0) { year++; // oops, meant -- } Loops run forever--must kill program

  16. Common Error: Off-by-1 Error • year = 0;while (balance < targetBalance){year++;double interest = balance * rate / 100;balance = balance + interest;}System.out.println("Reached target after "+ year + " years."); • Should year start at 0 or 1? • Should the test be < or <=?

  17. Avoiding Off-by-1 Error • Run through a simple example:target balance = $20,000, interest rate 50%after one year: balance = $15,000after two years: balance = $22,500Therefore: year must start at 0 • interest rate 100%after one year: balance = $20,000loop should stopTherefore: must use < • Think, don't compile and try at random

  18. do Statement • Executes loop body at least once: • do statementwhile (condition); • Example: Validate input • double value;do{ String input = JOptionPane.showInputDialog( "Please enter a positive number"); value = Integer.parseInt(input);} while (input <= 0);

  19. Flowchart for do Loop

  20. for Statement • for (initialization; condition; update)statement • Example: for (int i = 1; i <= n; i++){double interest = balance * rate / 100;balance = balance + interest;} • Equivalent toinitialization;while (condition){ statement; update; }

  21. Flowchart for for Loop

  22. File 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 {

  23. 7 /** 8 Constructs an Investment object from a starting balance and 9 interest rate. 10 @param aBalance the starting balanece 11 @param aRate the interest rate in percent 12 */ 13 public Investment(double aBalance, double aRate) 14 { 15 balance = aBalance;

  24. 16 rate = aRate; 17 years = 0; 18 } 19 20 /** 21 Keeps accumulating interest until a target balance has 22 been reached. 23 @param targetBalance the desired balance 24 */

  25. 25 public void waitForBalance(double targetBalance) 26 { 27 while (balance < targetBalance) 28 { 29 years++; 30 double interest = balance * rate / 100; 31 balance = balance + interest; 32 } 33 }

  26. 34 35 /** 36 Keeps accumulating interest for a given number of years. 37 @param n the number of years 38 */ 39 public void waitYears(int n) 40 {

  27. 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 } 48

  28. 49 /** 50 Gets the current investment balance. 51 @return the current balance 52 */ 53 public double getBalance() 54 { 55 return balance; 56 } 57

  29. 58 /** 59 Gets the number of years this investment has accumulated 60 interest. 61 @return the number of years since the start of the investment 62 */ 63 public int getYears() 64 { 65 return years; 66 }

  30. 67 68 private double balance; 69 private double rate; 70 private int years; 71 }

  31. File InvestmentTest.java 1 /** 2 This program computes how much an investment grows in 3 a given number of years. 4 */ 5 public class InvestmentTest 6 { 7 public static void main(String[] args) 8 { 9 final double INITIAL_BALANCE = 10000;

  32. 10 final double RATE = 5; 11 final int YEARS = 20; 12 Investment invest = new Investment(INITIAL_BALANCE, RATE); 13 invest.waitYears(YEARS); 14 double balance = invest.getBalance(); 15 System.out.println("The balance after " + YEARS + 16 " years is " + balance); 17 } 18 }

  33. Syntax 6.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

  34. Common Errors: Semicolons • A semicolon that shouldn't be theresum = 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);

  35. Nested Loops • Create triangle pattern[][][][][][][][][][] • Loop through rowsfor (int i = 1; i <= n; i++){// make triangle row}

  36. Make triangle row is another loopfor (int j = 1; j <= i; j++)r = r + "[]";r = r + "\n"; • Put loops together => Nested loops

  37. File Triangle.java 1 /** 2 This class describes triangle objects that can be displayed 3 as shapes like this: 4 [] 5 [][] 6 [][][] 7 */

  38. 8 public class Triangle 9 { 10 /** 11 Constructs a triangle. 12 @param aWidth the number of [] in the last row of the triangle. 13 */ 14 public Triangle(int aWidth) 15 { 16 width = aWidth; 17 }

  39. 18 19 /** 20 Computes a string representing the triangle. 21 @return a string consisting of [] and newline characters 22 */ 23 public String toString() 24 { 25 String r = "";

  40. 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 }

  41. File TriangleTest.java 1 /** 2 This program tests the Triangle class. 3 */ 4 public class TriangleTest 5 { 6 public static void main(String[] args) 7 { 8 Triangle small = new Triangle(3); 9 System.out.println(small.toString());

  42. 10 11 Triangle large = new Triangle(15); 12 System.out.println(large.toString()); 13 } 14 }

  43. 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"

  44. File DataSet.java 1 /** 2 Computes the average of a set of data values. 3 */ 4 public class DataSet 5 { 6 /** 7 Constructs an empty data set. 8 */

  45. 9 public DataSet() 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 */

  46. 20 public void add(double x) 21 { 22 sum = sum + x; 23 if (count == 0 || maximum < x) maximum = x; 24 count++; 25 } 26 27 /** 28 Gets the average of the added data. 29 @return the average or 0 if no data has been added 30 */

  47. 31 public double getAverage() 32 { 33 if (count == 0) return 0; 34 else return sum / count; 35 } 36 37 /** 38 Gets the largest of the added data. 39 @return the maximum or 0 if no data has been added 40 */

  48. 41 public double getMaximum() 42 { 43 return maximum; 44 } 45 46 private double sum; 47 private double maximum; 48 private int count; 49 }

  49. File InputTest.java 1 import javax.swing.JOptionPane; 2 3 /** 4 This program computes the average and maximum of a set 5 of input values. 6 */ 7 public class InputTest 8 {

  50. 9 public static void main(String[] args) 10 { 11 DataSet data = new DataSet(); 12 13 boolean done = false; 14 while (!done) 15 { 16 String input = JOptionPane.showInputDialog("Enter value, Cancel to quit"); 17 if (input == null) 18 done = true;

More Related