880 likes | 1.14k Views
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.
E N D
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 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
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 }
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
Investment with Compound Interest Invest $10,000, 5% interest, compounded annually When will the balance be at least $20,000?
while Statement while (condition)statement;repeats the statement while the condition is truewhile (balance < targetBalance){year++;double interest = balance * rate / 100;balance += interest;}
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; } }
Common Error: Infinite Loop while (year < 20) { balance += balance * rate / 100; } while (year > 0) { year++; // oops, meant -- } Loops run forever--must terminate program
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 <=?
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
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
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); } }
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.
Rewrite as a while loop. int sum = 0; for(int x = 1; x <= 10; x++) { sum += x; }
Rewrite as a while loop. int sum = 0; for(int x = 1; x <= 10; x++) { sum += x; } the result?
Rewritten as a while: int sum = 0; int x = 1; while(x <= 10) { sum+=x; x++; }
Rewrite as a for loop. int sum = 0; int x = 0; while (x <= 10) { System.out.println("X"); x++; }
Rewritten as a for loop int sum = 0; for(int x = 0; x <= 10; x++) { System.out.println(“X”); }
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);
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) ?
Flowchart for do Loop Do Statement(s) While condition True False
Rewrite as do…while loop for (int x = 1; x <= 10; x++) { sum += x; }
Rewrite as do…while loop for (int x = 1; x <= 10; x++) { sum += x; } int x = 1; do { sum += x; x++; } while (x <= 10);
Know when to use each type of loop! • for loop • while loop • do..while loop
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
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.
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
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?
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
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; } }
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
Give output: * ** *** **** for(int d=1; d<=4; d++) { System.out.println(); for(int a=1; a<=d; a++) { System.out.print("*"); } }
See File Triangle.javaandFile TriangleRunner.javapages 245-246 in your textbook
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.
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 }
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; }
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"
Guidance Ideas??? • How many characters does original have? original.length() characters
Guidance • How do we instantiate a newString with 0 characters?
Guidance • How do we instantiate a newString with 0 characters? String rev = ""; or String rev = new String();
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
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
Guidance • How do we build the new String? • Concatenate: rev += original.charAt(current); or rev += original.substring(current, current + 1);
Guidance • How do we return the answer? return rev;
Is a word a palindrome…… Algorithm(s) ????????????????
Is a word a palindrome…… public booleanisPalindrome() { }
Is a word a palindrome…… public booleanisPalindrome() {String rev = reverse(); return rev.equals(original); }