Post on 01-Jan-2016
Loops and Iteration
for Statements,while Statements anddo-while Statements
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 2
Loops Sometimes we want to execute a
statement or a group of statements repeatedly
Java structures for loops: for statement while statement do-while statement
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 3
Example applyInterest() method in BankAccount
(takes an intRate parameter)
public class BankAccount{ double balance; // make balance double so it can handle centavos ... public void applyInterest( double intRate ) { double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” +
balance ); } ...}
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 4
Compounding Interest Suppose interest is computed monthly but
compounded quarterlypublic void applyQtrlyInterest( double intRate ){ double interest; interest = balance*intRate/100; balance += interest; System.out.println( “Month 1 - interest:” + interest +”, balance:” + balance ); interest = balance*intRate/100; balance += interest; System.out.println( “Month 2 - interest:” + interest +”, balance:” + balance ); interest = balance*intRate/100; balance += interest; System.out.println( “Month 3 - interest:” + interest +”, balance:” + balance );}
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 5
Repeated Execution We want a way to indicate that the
following should be executed three times: interest = balance*intRate/100; balance += interest; System.out.println( “Monthly-interest:” + interest +”, balance:” +
balance );
Better still, we want the following executed where i takes the value 1, 2, 3:
interest = balance*intRate/100; balance += interest; System.out.print( “Month ” + i + “- interest: “+ interest ); System.out.println( “, balance:” + balance );
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 6
The for Statement Syntax
for ( expr1; expr2; expr3 ) statement
Notes expr1: initialization or setup (e.g., i = 1 ) expr2: condition (e.g., i <= 3 ) expr3: increment (e.g., i++) statement means any valid statement in
Java (including blocks)
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 7
Compounding Interestpublic void applyQtrlyInterest( double intRate ){ double interest; int i; for( i = 1; i <= 3; i++) { interest = balance*intRate/100; balance += interest; System.out.print( “Month ” + i + “- interest: “+ interest ); System.out.println( “, balance:” + balance );
}}
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 8
Another Example: Factorial
Given an integer n, compute n! We want: result = 1*2*3*…*n; Repeated operation(s)
multiply a number i to result increment the number i
Do n times starting with i = 1, result = 1:
result = result * i;i = i + 1;
Looping code aka “Iterative” code one round of the loop is called an “iteration”
properly pronounced “ih-teration” not “eye-teration”(think of how you say “reiterate”)
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 9
The while Statement
public int factorial( int n ){ int result = 1; int i = 1; while ( i <= n ) { result = result * i; i = i + 1; }
return result;}
Condition
Loop Body
Setup
Increment / Go to next step
Syntax: while ( condition )statement
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 10
The do-while Statement
public int factorial( int n )
{
int result = 1;
int i = 1;
do
{
result = result * i;
i = i + 1;
} while ( i <= n );
return result;
}
Condition(at the end of loop)
Loop Body
Setup
Increment / Go to next step
Syntax: dostatement
while ( condition );
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 11
Components of a Loop Setup/Initialization Terminating/Continuing condition Incrementing step
not necessarily an increment, but something that moves the program further on – i.e., to a state possibly closer to a terminating condition
e.g., decrementing, dividing, multiplitying, getting another input, etc.
Loop body
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 12
Using a for loop for factorial
public int factorial( int n ){ int result = 1; int i; for ( i = 1; i <= n; i++ ) { result = result * i; }
return result;}
Condition
Loop Body
Setup
Increment / Go to next step
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 13
for loop (version 2)public int factorial( int n ){ int result;
result = 1;
for ( int i = 1; i <= n; i++ ) { result = result * i; }
return result;}
You can declare the “counter” variable inside the for scope is within the loop’s block
good when i is not used outside of the loop
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 14
for loop (version 3)
public int result( int n ){ int i, result;
for ( result = 1, i = 1; i <= n; i++ ) { result = result * i; }
return result;}
You can have multiple statements in “setup” part of for separated by commas
need to declare the variables before the for, since we can’t have declarations here
also works for increment part
NOT RECOMMENDED! generally bad style to put several statements on one line
if possible, choose a single counter variable, and just use that
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 15
for loop (version 3b)public int factorial( int n ){ int i, result;
for ( result = 1, i = 1; i <= n; result *= i, i++ ) { }
return result;}
This is legal, but BAD! cryptic
the for loop has no body!
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 16
for loop (version 3w)public int factorial( int n ){ int i, result;
for ( result = 1, i = 1; i <= n; result *= i++ ) { }
return result;}
(“w” for worse!) even more cryptic
Some C programmers actually like writing like this!
DON’T!
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 17
for and while are equivalent!
public int factorial( int n )
{
int result;
result = 1;
{
int i = 1;
while ( i <= n )
{
result = result * i;
i++;
}
}
return result;
}
public int factorial( int n ){ int result;
result = 1; for ( int i = 1; i <= n; i++ ) { result = result * i; }
return result;}
Setup
Condition
Increment
Braces here are shown becausein Java (not in C), scope of vars declared in setup of foris limited
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 18
Deciding which statement to use
Using a for statement most appropriate when the number of
iterations is known (e.g., factorial of n) Difference between while and do-while
loop condition is performed at the top (while) or at the bottom (do-while) of the loop
in do-while, body is executed at least once in while, we check first before executing
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 19
Nested Loops It is possible to have a loop within a
loop Example (What gets printed out?)
for ( int i = 0; i < 5; i++ )
{
System.out.println( i );
for ( int j = 0; j < 5; j++ )
{
System.out.println( j );
}
}
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 20
Nested Loops The condition can vary depending on
the outer loop Example (What gets printed out?)
for ( int i = 0; i < 5; i++ ) { System.out.println( i ); for ( int j = 0; j < i; j++ ) { System.out.print( j ); } System.out.println( “” );}
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 21
Loop Pitfall # 1
Infinite Loops
Both loops will not terminate because the boolean expressions will never become false.
Infinite Loops
Both loops will not terminate because the boolean expressions will never become false.
int count = 1;
while ( count != 10 ) {
count = count + 2;
}
22
int product = 0;
while ( product < 500000 ) {
product = product * 5;
}
11
examples and slide adapted from Introduction to Object Oriented Programming with Java by C. Thomas Wu, Copyright 2000, McGraw-Hill
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 22
Loop Pitfall # 2Using Real Numbers
Loop 2 terminates, but Loop 1 does not because a float or double is only an approximation of a real number. Operations are not necessarily exact.
Using Real Numbers
Loop 2 terminates, but Loop 1 does not because a float or double is only an approximation of a real number. Operations are not necessarily exact.
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.33333333f;
} //eight 3s
22
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.3333333f;
} //seven 3s
11
examples and slide adapted from Introduction to Object Oriented Programming with Java by C. Thomas Wu, Copyright 2000, McGraw-Hill
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 23
Loop Pitfall - 3 Goal: Execute the loop body 10 times.
count = 1;
while ( count < 10 ) {
. . .
count++;
}
11
count = 0;
while ( count <= 10 ) {
. . .
count++;
}
33
count = 1;
while ( count <= 10 ) {
. . .
count++;
}
22
count = 0;
while ( count < 10 ) {
. . .
count++;
}
44
11 33and exhibit off-by-one error (OBOE).examples and slide adapted from Introduction to Object Oriented Programming with Java by C. Thomas Wu, Copyright 2000, McGraw-Hill
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 24
Avoiding Pitfalls Infinite Loop
loop body or increment statement should contain a statement that eventually leads to termination
Real Numbers Avoid using == or != when using real numbers Use <= or >= depending on direction of loop
OBOE (Off-By-One-Error) aka “Fencepost error” To execute the loop body N times …
if counter starts at 0, check for counter < N if counter starts at 1, check for counter <= N
Remember that after the loop, the counter (if still in scope) will be beyond the limit of your condition
if we started from 0, counter would be N, if we started from 1, counter would be N+1
6/28/2004Copyright 2004, by the authors of these slides, and Ateneo
de Manila University. All rights reserved L9: Loops
Slide 25
Some Exercises Using Loops
List all even numbers less than a given limit Approach 1: Use an if-statement inside a for-
loop Approach 2: Arrange it so that the for-loop does
skips through the odd numbers Print out all 16 pairs of numbers from the
set {0,1,2,3} What if the numbers have to be distinct? What if the the order does not matter (i.e., the
pair 1,2 is the same as the pair 2,1) Print out a block of asterisks of a given size