Presentation is loading. Please wait.

Presentation is loading. Please wait.

Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.

Similar presentations


Presentation on theme: "Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006."— Presentation transcript:

1 Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. while (chapter < 8) chapter++;

2 8-2 Objectives: Understand the semantics and learn the Java syntax for while, for, and do-while loops Learn how to use nested loops

3 8-3 Iterations It is essential that a program be able to execute the same set of instructions many times: otherwise a computer would do 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.

4 8-4 The while Loop while ( condition ) { statement1; statement2;... statementN; } while ( condition ) statement1; If the body has only one statement, the braces are optional condition is any logical expression, as in if The body of the loop

5 8-5 // 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; } The while Loop (cont’d) Example: Initialization Testing Change

6 8-6 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.

7 8-7 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

8 8-8 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 = 2 n

9 8-9 The for Loop for is a shorthand that combines in one statement initialization, condition, and change: for ( initialization; condition; change ) { statement1; statement2;... statementN; }

10 8-10 // 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; } The for Loop (cont’d) Example: Initialization Testing Change

11 8-11 The for Loop (cont’d) Java allows you to declare the loop control variable in the for statement itself. For example: for (int i = 0; i < n ; i++) {... } The scope of i is the body of the loop, and i is undefined outside the loop

12 8-12 The for Loop (cont’d) “Repeat n times” idiom: or for (int i = 0; i < n ; i++) {... } for (int count = 1; count <= n ; count++) {... }

13 8-13 The for Loop (cont’d) Example: n! = 1 * 2 *... * n /** * Returns 1 * 2 *... * n, if n >= 1 (and 1 otherwise) */ public static long factorial (int n) { long f = 1; for (int k = 2; k <= n; k++) f * = k; return f; }

14 8-14 The do-while Loop do { statement1; statement2;... statementN; } while ( condition ); The code runs through the body of the loop at least once Always use braces for readability (even if the body has only one statement) if condition is false, the next iteration is not executed

15 8-15 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; do { str = file.readLine();... } while (str != null);

16 8-16 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();... }

17 8-17 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.

18 8-18 break in Loops Example: int d = n - 1; while (d > 0) { if (n % d == 0) break; d -- ; } if ( d > 0 ) // if found a divisor...

19 8-19 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; }

20 8-20 Nested Loops A loop within a loop is called nested. // Draw a 5 by 3 grid: for (int x = 0; x < 50; x += 10) { for (int y = 0; y < 30; y += 10) { g.fillRect(x, y, 8, 8); }

21 8-21 Nested Loops (cont’d) Braces are optional when the body of the loop(s) is one statement: for (int x = 0; x < 100; x += 10) for (int y = 0; y < 200; 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.

22 8-22 Nested Loops (cont’d) Be careful with break: int r, c; for (r = 0; r < m.length; r++) { for (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

23 8-23 “Triangular” Nested Loops “Find duplicates” idiom: 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 ] ); } The inner lcv starts at the outer lcv’s next value

24 8-24 Lab: Perfect Numbers A perfect number is a positive integer equal to the sum of all its divisors (including 1 but excluding the number itself). For example: 28 = 1 + 2 + 4 + 7 + 14 Write a program to find the first four perfect numbers (Java Methods A & AB pp. 204-205).

25 8-25 Lab: Perfect Numbers (cont’d) Euclid showed that if 2 n - 1 is a prime, then 2 n - 1 (2 n - 1) is a perfect number. For example: 2 3 - 1 = 7 is a prime => 2 2 (2 3 - 1) = 28 is a perfect number Euclid Around 300 BC

26 8-26 Lab: Perfect Numbers (cont’d) A prime that has a form 2 n - 1 is called a Mersenne prime. Marin Mersenne 1588-1648 Leonhard Euler 1707-1783 Write a program to find the first six Mersenne primes and the corresponding perfect numbers. Euler proved that any even perfect number must have that form.

27 8-27 Lab: Perfect Numbers (cont’d) The 44th Mersenne Prime, 2 32,582,657 - 1 = 12457502601536945540... 11752880154053967871 (9,808,358 digits), was discovered in September 2006. There is a $100,000 reward for finding a 10 million digit prime number. http://www.mersenne.org/32582657.htm

28 8-28 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?

29 8-29 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?


Download ppt "Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006."

Similar presentations


Ads by Google