1 / 88

Chapter 6

Chapter 6. Iteration . Chapter 6 Assignment 1. Read 6.1 – 6.5 Pages 276 – 278 # R6.2-6.5, R6.8 , R6.13 Due November 27, 2012 Loops and Nested Loops Worksheet Due November 30th. Read 6.6 – 6-.7 Page 278 do # R6.14 and R6.18 Due December 3rd. Chapter Goals.

daktari
Télécharger la présentation

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 6 Assignment 1 • Read 6.1 – 6.5 • Pages 276 – 278 # R6.2-6.5, R6.8, R6.13 • Due November 27, 2012 • Loops and Nested Loops Worksheet • Due November 30th. • Read 6.6 – 6-.7 • Page 278 do # R6.14 and R6.18 • Due December 3rd.

  3. 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 To use a debugger

  4. Conditional Control • The if statement and if/else statement allows a statement or a block of statements to be executed conditionally based on a Boolean test. if (grade >= 0 && grade <= 100) { //valid grade }

  5. Iterative Control: while • The while statement repeatedly executes a statement or block of statements while the Boolean test evaluates to true. int sum = 0; int numGrades = 0; //get grade from user while (grade >= 0 && grade <= 100) { sum += grade; numGrades++; //get grade from user } // find the average of the grades

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

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

  8. true true test test false false Statement list Next statement Statement list Next statement Semantics of while loop (Owen Astrachan:Tapestry) if (test) while (test) { { statements; statements; } }

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

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

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

  12. Developing Loops Owen Astrachan • Some loops are easy to develop code for, others are not. • Sometimes the proper loop test and body are hard to design. • Practice helps, but • Good design comes from experience; Experience comes from bad design. • There are other looping statements in addition to while, but they don’t offer anything more powerful, just some syntactic convenience. • for loop • do-while loop

  13. The for loop • Many times, the exact number of iterations is known before loop begins. This indicates that a for loop may be our best choice. • public void moveCat(int x) { final int OFF_SCREEN = 30; final int SMALL_AMOUNT = 2; for(int y = 1; y <= OFF_SCREEN; y++) { face.moveHorizontal(SMALL_AMOUNT); body.moveHorizontal(SMALL_AMOUNT); ear1.moveHorizontal(SMALL_AMOUNT); ear2.moveHorizontal(SMALL_AMOUNT); leg1.moveHorizontal(SMALL_AMOUNT); leg2.moveHorizontal(SMALL_AMOUNT); } }

  14. The while loop – The for loop int k = 0; for(int k=0; k < TIMES; k++) while (k < TIMES) { {// do stuff // do stuff; } k += 1; } • The for loop has the initialization, test, update in one place.

  15. Flowchart for for Loop

  16. Rewrite as a while loop. int sum = 0; for(int x = 1; x <= 10; x++) { sum += x; }

  17. Rewrite as a while loop. int sum = 0; for(int x = 1; x <= 10; x++) { sum += x; } the result?

  18. Rewritten as a while: int sum = 0; int x = 1; while(x <= 10) { sum+=x; x++; }

  19. Rewrite as a for loop. int sum = 0; int x = 0; while (x <= 10) { System.out.println("X"); x++; }

  20. Rewritten as a for loop int sum = 0; for(int x = 0; x <= 10; x++) { System.out.println(“X”); }

  21. 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);

  22. The do-while loop • The while loop may never execute, some loops should execute at least once. do { // enter a grade } while (grade < 0 || 100 < grade); • Execute while the test/guard is true, in example above what must be true when loop terminates (de Morgan) ?

  23. Flowchart for do Loop Do Statement(s) While condition True False

  24. Rewrite as do…while loop for (int x = 1; x <= 10; x++) { sum += x; }

  25. Rewrite as do…while loop for (int x = 1; x <= 10; x++) { sum += x; } int x = 1; do { sum += x; x++; } while (x <= 10);

  26. Know when to use each type of loop! • for loop • while loop • do..while loop

  27. Know when to use each type of loop! • for loop • you know exactly how many times loop is to be executed. • while loop • loop may be executing zero times • do..while loop • loop must execute at least once

  28. Scope of for loop variables • If a variable is declared in the for loop header, its scope extends to the end of the for loop. for(intx = 1; x <= n; x++) { // x can be accessed here } // x is no longer defined.

  29. Scope of for loop variables • If a variable is declared outside the for loop header, its scope extends outside the end of the for loop. int x; for(x = 1; x <= n; x++) { // x can be accessed here } // x is still in scope here

  30. Nested loops • Sometimes one loop occurs in another • Generating tables for(int row = 1; row <= 6; row++) { for(intcol = 1; col <= 6; col++) { System.out.print ("\t" + row*col); } System.out.println(); } • What’s printed? What’s the purpose of the inner loop?

  31. Nested loops for(int row = 1; row <= 6; row++) { for(intcol = 1; col <= 6; col++) { System.out.print ("\t" + row*col); } System.out.println(); }1 2 3 4 5 6 2 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 6 12 18 24 30 36

  32. Practice int i, j, product; int sum = 0; for (int i = 1; i <= 4; i++) { for (j = 1; j <= 3; j++) { product = i * j; sum += product; } }

  33. More Practice int x, y, z; for (x = 1; x <= 2; x++) for (y = 1; y <= 2; y++) for (z = 1; z <= 2; z++) System.out.println(x + " " + y + " " + z) //OUTPUT 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 y z x

  34. Give output: * ** *** **** for(int d=1; d<=4; d++) { System.out.println(); for(int a=1; a<=d; a++) { System.out.print("*"); } }

  35. See File Triangle.javaandFile TriangleRunner.javapages 245-246 in your textbook

  36. Chapter 6 Assignment 1 • Read 6.1 – 6.5 • Pages 276 – 278 # R6.2-6.5, R6.8, R6.13 • Due November 27, 2012 • Loops and Nested Loops Worksheet • Due November 30th. • Read 6.6 – 6-.7 • Page 278 do # R6.14 and R6.18 • Due December 3rd.

  37. Consider the following incomplete Wordclass. public class Word { public Word(String s) { original = s; // more may eventually be added here } // code goes here private String original; // more may eventually be added here }

  38. The incomplete Wordclass. public class Word { public Word(String s) { original = s; } // returns the reverse of original public String reverse() { //code goes here } // more code goes here private String original; }

  39. Write a Word method to return a String that is the reverse of the Word's original String value. public String reverse() { } Word w = new Word("math"); w.reverse() returns "htam"

  40. Guidance Ideas??? • How many characters does original have? original.length() characters

  41. Guidance • How do we instantiate a newString with 0 characters?

  42. Guidance • How do we instantiate a newString with 0 characters? String rev = ""; or String rev = new String();

  43. Guidance • How do we access one letter of the String original? The ith character of original is: original.charAt(i) returns a char or original.substring(i, i+1) returns a String

  44. Guidance • How do we traverse the original String in reverse order? • Use a while loop starting with the last character of original: • int current = original.length()–1; • position of last letter in original • while (current >= 0) • get the current character of original • decrement current

  45. Guidance • How do we build the new String? • Concatenate: rev += original.charAt(current); or rev += original.substring(current, current + 1);

  46. Guidance • How do we return the answer? return rev;

  47. Write method reverse().

  48. Is a word a palindrome…… Algorithm(s) ????????????????

  49. Is a word a palindrome…… public booleanisPalindrome() { }

  50. Is a word a palindrome…… public booleanisPalindrome() {String rev = reverse(); return rev.equals(original); }

More Related