Chapter 8 - Iterative statements: while, for, do–while. In this chapter, the learning objectives are: Understand the semantics and learn the Java syntax for while, for, and do-while loops; learn how to use nested loops.
Java Methods Object-Oriented Programming and Data Structures 2nd AP edition with GridWorld Maria Litvin ● Gary Litvin while (chapter < 8) chapter++; Iterative Statements: while, for, do-while Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing All rights reserved Objectives: • Understand the semantics and learn the Java syntax for while, for, and do-while loops • Learn how to use nested loops 82 Iterations • It is essential that a program be able to execute the same set of instructions many times: otherwise a computer would only as much work as a programmer! • Repeating the same code fragment several times is called iterating • Java provides three control statements for iterations (a.k.a loops): for, while, and do-while 83 The while Loop condition is any logical expression, as in if while ( condition ) { statement1; statement2; statementN; } The body of the loop If the body has only one statement, the braces are optional while ( condition ) statement1; 84 The while Loop (cont’d) • Example: // Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p = 1; while ( p < x ) { p *= 2; n++; } return n; Initialization Testing Change } 85 The while Loop (cont’d) • Initialization: The variables tested in the condition must be initialized to some values If the condition is false at the outset, the loop is never entered • Testing: The condition is tested before each iteration If false, the program continues with the first statement after the loop • Change: At least one of the variables tested in the condition must change within the body of the loop 86 The while Loop (cont’d) • Sometimes change is implicit in the changed state of a variable: Scanner input = new Scanner(inputFile); while (input.hasNext()) System.out.println ( input.next( ) ); Changes the state of input 87 Loop Invariants • A loop invariant is an assertion that is true before the loop and at the end of each iteration • Invariants help us reason about the code int n = 0, p = 1; while (p < x) { p *= 2; n++; } Loop invariant: p = 2n 88 The for Loop • for is a shorthand that combines in one statement initialization, condition, and change: for ( initialization; condition; change ) { statement1; statement2; statementN; } 89 The for Loop (cont’d) • Example: // Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p; for (p = 1; p < x; p *= 2) { n++; } return n; Initialization Testing Change } 810 The do-while Loop (cont’d) • do-while is convenient when the variables tested in the condition are calculated or read in the body of the loop: String str; { str = file.readLine(); } while (str != null); 815 The do-while Loop (cont’d) • do-while can be easily avoided: we can usually replace it with a while loop initialized so that it goes through the first iteration: String str = "dummy"; while (str != null) { str = file.readLine(); } 816 break and return in Loops • break in a loop instructs the program to immediately quit the current iteration and go to the first statement following the loop • return in a loop instructs the program to immediately quit the current method and return to the calling method • A break or return must be inside an if or an else, otherwise the code after it in the body of the loop will be unreachable 817 break in Loops • Example: int d = n - 1; while (d > 0) { if (n % d == 0) break; d ; } if ( d > ) // if found a divisor 818 return in Loops • Sequential Search method: public int search(String[ ] list, String word) { for (int k = 0; k < list.length; k++) { if (list[k].equals (word) return k; } } return -1; 819 Nested Loops • A loop within a loop is called nested // Draw a by grid: for (int x = 0; x < 50; x += 10) { for (int y = 0; y < 30; y += 10) { g.fillRect(x, y, 8, 8); } } 820 Nested Loops (cont’d) • Braces are optional when the body of the loop(s) is one statement: for (int x = 0; x < 50; x += 10) for (int y = 0; y < 30; y += 10) g.fillRect(x, y, 8, 8); Inner for is the only statement in the outer for’s body • Many programmers prefer to always use braces in loops, especially in nested loops 821 Nested Loops (cont’d) • Be careful with break: for (int r = 0; r < m.length; r++) { for (int c = 0; c < m[0].length; c++) { if (m [ r ][ c ] == 'X' ) break; } } Breaks out of the inner loop but continues with the outer loop 822 “Triangular” Nested Loops • “Find duplicates” idiom: The inner lcv starts at the outer lcv’s next value for (int i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) { if (a [ i ].equals(a [ j ]) System.out.println ("Duplicate " + a [ j ] ); } } 823 Lab: Perfect Numbers • A perfect number is a positive integer equal to the sum of all its divisors (including but excluding the number itself) For example: 28 = + + + + 14 Write a program to find the first four perfect numbers (Java Methods pp 210-211) 824 Lab: Perfect Numbers (cont’d) • Euclid showed that if 2n-1 is a prime, then 2n-1(2n-1) is a perfect number For example: 23-1 = is a prime => 22(23-1) = 28 is a perfect number Euclid Around 300 BC 825 Lab: Perfect Numbers (cont’d) • A prime that has a form 2n-1 is called a Mersenne prime Leonhard Euler 1707-1783 • Euler proved that any Marin Mersenne 1588-1648 even perfect number must have that form Write a program to find the first six Mersenne primes and the corresponding perfect numbers 826 Lab: Perfect Numbers (cont’d) • The largest known Mersenne Prime is 243,112,609 – It has 12,978,189 digits It was discovered by GIMPS (Great Internet Mersenne Prime Search) particiants at UCLA in 2008 • They also claimed the Electronic Frontier Foundation’s $100,000 prize for finding a prime number with more than 10 million digits http://www.mersenne.org 827 Review: • Name three iterative control statements in Java • What is the difference between while and do-while? • Can any code with a for loop be rewritten with a while loop? • Does short-circuit evaluation apply to conditions in loops? • Which operators can be used in the “change” part of a for loop? 828 Review (cont’d): • Are method calls allowed in a condition in a while loop? • Is return allowed in a loop? • What is a nested loop? • Name a situation where nested loops are used • Can you have nested while loops? 829 ... numbers (Java Methods pp 21 0-2 11) 8? ?24 Lab: Perfect Numbers (cont’d) • Euclid showed that if 2n-1 is a prime, then 2n-1(2n-1) is a perfect number For example: 2 3-1 = is a prime => 22(2 3-1 ) = 28 is... Around 300 BC 8? ?25 Lab: Perfect Numbers (cont’d) • A prime that has a form 2n-1 is called a Mersenne prime Leonhard Euler 170 7-1 783 • Euler proved that any Marin Mersenne 1 588 -1 6 48 even perfect...Objectives: • Understand the semantics and learn the Java syntax for while, for, and do-while loops • Learn how to use nested loops 8? ?2 Iterations • It is essential that a