iterative statements: while, for, do-while java methods a & ab object-oriented programming and...

29
Iterative Statements: while, for, do-while Java Methods Java Methods A & AB 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++;

Upload: sherilyn-lloyd

Post on 17-Jan-2016

222 views

Category:

Documents


0 download

TRANSCRIPT

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

Iterative Statements: while, for, do-while

Java MethodsJava MethodsA & ABA & AB

Object-Oriented Programmingand Data Structures

Maria Litvin ● Gary Litvin

Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

while (chapter < 8) chapter++;

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

8-2

Objectives:

• Understand the semantics and learn the Java syntax for while, for, and do-while loops

• Learn how to use nested loops

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

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.

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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++) { ... }

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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); } }

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

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.

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

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

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

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

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

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

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

8-25

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 = 7 is a prime =>

22(23-1) = 28 is a perfect number Euclid

Around 300 BC

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

8-26

Lab: Perfect Numbers (cont’d)• A prime that has a form 2n-1

is called a Mersenne prime.

Marin Mersenne1588-1648

Leonhard Euler1707-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.

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

8-27

Lab: Perfect Numbers (cont’d)

• The 44th Mersenne Prime, 232,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

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

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?

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

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?