Download presentation
Presentation is loading. Please wait.
Published byGwendoline Allen Modified over 5 years ago
1
Loops and Iteration CS 21a: Introduction to Computing I
Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 6, Horstmann text)
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 Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
3
Example applyInterest() method in BankAccount (takes an intRate parameter) public class BankAccount { double balance; ... public void applyInterest( double intRate ) double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
4
Example applyInterest() method in BankAccount (takes an intRate parameter) public class BankAccount { double balance; ... public void applyInterest( double intRate ) double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } Shorthand for: balance = balance + interest; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
5
Example improved Let’s add attributes for interest rate and years
public class BankAccount { double balance; double intRate; // interest rate on balance int years; // age of bank account public void applyInterest( ) double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } ... Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
6
Example – yearly interest
yearlyInterest() method in BankAccount public class BankAccount { ... public void yearlyInterest() double interest = balance*intRate/100; balance += interest; years++; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
7
Repeatedly applying interest
Suppose you want to apply interest on the balance for three years public void applyThreeYearInterest( ) { double interest; interest = balance*intRate/100; balance += interest; years++; System.out.println( “Year 1 - interest:” + interest +”, balance:” + balance ); System.out.println( “Year 2 - interest:” + interest +”, balance:” + balance ); System.out.println( “Year 3 - interest:” + interest +”, balance:” + balance ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
8
Repeated execution We want a way to indicate that the following should be executed three times: interest = balance*intRate/100; balance += interest; years++; System.out.println( “Yearly-interest:” + interest +”, balance:” + balance ); Better still, we want the following executed where i takes the value 1, 2, 3: System.out.print( “Year ” + i + “- interest: “+ interest ); System.out.println( “, balance:” + balance ); Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
9
The for statement Syntax Notes for ( expr1; expr2; expr3 ) statement
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) Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
10
Applying yearly interest
public void applyYearlyInterest( int numYears ) { double interest; int i; for( i = 1; i <= numYears; i++) interest = balance*intRate/100; balance += interest; System.out.print( “Year ” + i + “- interest: “+ interest ); System.out.println( “, balance:” + balance ); years++; } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
11
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” Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
12
The while statement Setup Condition Loop Body Increment /
Syntax: while ( condition ) statement Setup 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 Increment / Go to next step Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
13
The do-while Statement
Syntax: do statement while ( condition ); public int factorial( int n ) { int result = 1; int i = 1; do result = result * i; i = i + 1; } while ( i <= n ); return result; } Setup Loop Body Increment / Go to next step Condition (at the end of loop) Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
14
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 Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
15
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; Setup Condition Loop Body Increment / Go to next step Increment / Go to next step Increment / Go to next step Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
16
for loop (version 2) 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 public int factorial( int n ) { int result; result = 1; for ( int i = 1; i <= n; i++ ) result = result * i; } return result; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
17
for loop (version 3) 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 public int result( int n ) { int i, result; for ( result = 1, i = 1; i <= n; i++ ) result = result * i; } return result; NOT RECOMMENDED! generally bad style to put several statements on one line if possible, choose a single counter variable, and just use that Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
18
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! Shorthand for: result = result*i; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
19
for loop (version 3w) (“w” for worse!) public int factorial( int n ) {
even more cryptic Some C programmers actually like writing like this! DON’T! public int factorial( int n ) { int i, result; for ( result = 1, i = 1; i <= n; result *= i++ ) } return result; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
20
for and while are equivalent!
public int factorial( int n ) { int result; result = 1; for ( int i = 1; i <= n; i++ ) result = result * i; } return result; public int factorial( int n ) { int result; result = 1; int i = 1; while ( i <= n ) result = result * i; i++; } return result; Setup Braces here are shown because in Java (not in C), scope of vars declared in setup of for is limited Condition Increment Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
21
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 Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
22
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 ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
23
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( ); Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
24
Loop Pitfall # 1 Infinite Loops 1
int years = 0; while ( years < 20 ) { double interest = balance * rate / 100; balance = balance + interest; } 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int years = 20; while ( years > 0 ) { years++; double interest = balance * rate / 100; balance = balance + interest; } 2 Note: In theory, this while statement is an infinite loop, but in programming languages other than Java, this loop will eventually terminate because of an overflow error. An overflow error will occur if you attempt to assign a value larger than the maximum value the variable can hold. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. With Java, however, an overflow will not cause the program termination. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. examples adapted from Chapter 6 of Java Concepts by C. Horstmann Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
25
Loop Pitfall # 2 Using Real Numbers 1 2
float count = 0.0f; while ( count != 1.0f ) { count = count f; } //seven 3s 1 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 f; } //eight 3s 2 Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/ / /3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision. examples and slide adapted from Introduction to Object Oriented Programming with Java by C. Thomas Wu, Copyright 2000, McGraw-Hill Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
26
Loop Pitfall – 3 Goal: Execute the loop body 10 times. 1 2 3 4 1 3 and
count = 1; while ( count < 10 ) { . . . count++; } 1 count = 1; while ( count <= 10 ) { . . . count++; } 2 count = 0; while ( count <= 10 ) { . . . count++; } 3 count = 0; while ( count < 10 ) { . . . count++; } 4 Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop. 1 3 and 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 Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
27
Avoiding pitfalls Infinite Loop Real Numbers
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 Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
28
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) Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
29
Printing a shape Create a triangle pattern * ** *** Loop through rows
for (int i = 1; i <= n; i++) { // make triangle row } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
30
Printing a shape – cont. The following loop creates a row of i stars
for (int j = 1; j <= i; j++) r = r + "*"; r = r + "\n"; Put loops together → Nested loops String r = "" ; for (int i = 1; i <= n; i++) { // make triangle row } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
31
Triangle class public class Triangle { private int width;
public Triangle(int aWidth) width = aWidth; } public String toString() String r = ""; for (int i = 1; i <= width; i++) for (int j = 1; j <= i; j++) r = r + "*"; r = r + "\n"; return r; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
32
TriangleRunner class public class TriangleRunner {
public static void main(String[] args) Triangle small = new Triangle(3); System.out.println(small.toString()); Triangle large = new Triangle(15); System.out.println(large.toString()); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
33
Exercises for nested loops
Create similar classes that print out these shapes as well: * * * * Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.