42
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Embed Size (px)

Citation preview

Page 1: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Loops: Handling Infinite

ProcessesCS 21a: Introduction to

Computing IFirst Semester, 2013-2014

Page 2: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s a Loop?

►A way to express a constant number of repetitions

►A way to express an arbitrary number of repetitions, usually based on some input value or condition

Page 3: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Loops

►Java structures for loops:►for statement►while statement►do-while statement

Page 4: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Example: Compound Interest

public class BankAccount

{

...

public void yearlyInterest()

{

double interest = balance*intRate/100;

balance += interest;

years++;

println( "Interest:" + interest

+ ", balance is now" + balance );

}

...

}

Page 5: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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++; println( "Year 1 - interest:" + interest + ", balance:" + balance ); interest = balance*intRate/100; balance += interest; years++; println( "Year 2 - interest:" + interest + ", balance:" + balance ); interest = balance*intRate/100; balance += interest; years++; println( "Year 3 - interest:" + interest + ", balance:" + balance );}

Page 6: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Repeated Execution

► We want a way to indicate that the following should be executed three times:

interest = balance*intRate/100;

balance += interest;

years++;

println( "Yearly-interest:" + interest + ", balance:" + balance );

► Better still, we want the following executed where takes the value 1, 2, 3:

interest = balance*intRate/100;

balance += interest;

years++;

print( "Year " + i + "- interest: " + interest );

println( ", balance:" + balance );

Page 7: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

The Power of Loops

►Allow an arbitrarily long process to be described with a short algorithm

Page 8: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

The for Statement

► Syntaxfor ( 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)

Page 9: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Applying Yearly Interest 3 Times

public void applyThreeYearInterest( ){

double interest;

int i;

for( i = 1; i <= 3; i++)

{

interest = balance*intRate/100;

balance += interest;

print( "Year " + i + "- interest: " + interest );

println( ", balance:" + balance );

years++;

}

}

Page 10: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

First Use of Loops

►Express a repetitive process, where the number of repetitions is constant.►Problem can still be solved without

loops, but coding is too tedious without it.

►Becomes more useful as the constant grows larger.

Page 11: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Applying Yearly Interest An Arbitrary Number of Times

public void applyYearlyInterest( int numYears )

{

double interest;

int i;

for( i = 1; i <= numYears; i++)

{

interest = balance*intRate/100;

balance += interest;

print( "Year " + i + "- interest: " + interest );

println( ", balance:" + balance );

years++;

}

}

Page 12: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Second (More Important) Use of Loops

►Express a repetitive process whose length is based on some condition. Two possibilities…►Bounded iteration: Simply repeat

times, where is given►Conditional iteration: The number

of repetitions is not known in advance, but the length will always depend on some condition

Page 13: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

►Write a procedure/function that computes given a non-negative integer . Try not to cheat from the next slides!

and ►Bored? Try an alternate

implementation based on this definition:

Page 14: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

public int factorial( int n ){ int result = 1; int i = 1; while ( i <= n ) { result = result * i; i = i + 1; } return result;}

The while Statement

►Syntaxwhile ( condition ) statement

SetupCondition

Loop Body

Increment /go to next step

Page 15: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

public int factorial( int n )

{

int result = 1;

int i = 1;

do

{

result = result * i;

i = i + 1;

} while ( i <= n );

return result;

}

The do-while Statement

► Syntaxdo statementwhile ( condition );

Setup

Loop Body

Increment /go to next step

Condition

Page 16: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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

Page 17: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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

Page 18: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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 the loop

Page 19: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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 the "setup" part of for

separated by commasneed to declare the

variables before the for, since we can't have declarations here

also works for the 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

Page 20: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

for Loop (version 3b)public int factorial( int n ){ int i, result;

for ( result = 1, i = 1; i <= n; result *= i, i++ ) { }

return result;}

Shorthand for:result = result * i;

This is legal, but BAD!

cryptic The for loop has no

body!

Page 21: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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!

Page 22: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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;

}

Increment

Setup

Condition

Braces here are shown because in Java (not in C), scope of variables declared in setup of for is limited

Page 23: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Deciding which Statement to Use

► Using a for statement► most appropriate when the number of

iterations is easily known (e.g., factorial)► 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

Page 24: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

► Write a program that reads numbers from console input and prints them out, one on each line, until a zero is encountered (don’t print out the zero). Identify the setup, condition, and increment. Is this a bounded or a conditional iteration?

► Sample Input Sample Output1 2 3 1

4 5 2

0 3

4

5

Page 25: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

► Write a program that reads a positive integer and prints out all the positive integers, separated by spaces, up to an including . Is this a bounded or a conditional iteration?

► Sample Input

16► Sample Output

2 4 6 8 10 12 14 16

Page 26: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s Wrong with This Code

// assume grandmasFavoriteNumber is a positive integer

for(int i = 0; i != grandmasFavoriteNumber; i++)

;

println("It took " + i

+ " iterations to guess grandma's fave number.");

// What’s a better way to write this?

Page 27: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s Wrong with This Code?

int years = 0;

while ( years < 20 )

{

double interest = balance * rate / 100;

balance = balance + interest;

}

Page 28: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s Wrong with This Code?

int years = 20;

while ( years > 0 )

{

years++;

double interest = balance * rate / 100;

balance = balance + interest;

}

Page 29: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s Wrong with This Code?

float count = 0.0f;

while ( count != 1.0f ) {

count = count + 0.3333333f;

}

// How would you fix it?

Page 30: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s Wrong with This Code?

void derpNTimes(int n)

{

for(int i = 1; i < n; i++)

println("derp");

}

Page 31: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

What’s Wrong with This Code?

void derpNTimes(int n)

{

for(int i = 0; i <= n; i++)

println("derp");

}

Page 32: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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

Page 33: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Avoiding Pitfalls

► 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

Page 34: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Nested Loops

► It is possible to have a loop within a loop► Example (What gets printed out?)

for ( int i = 0; i < 5; i++ ) { println( i ); for ( int j = 0; j < 5; j++ ) { print(" " + j ); } println();}

Page 35: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Nested Loops► The condition can vary depending on the

outer loop► Example (What gets printed out?)

for ( int i = 0; i < 5; i++ ) { println( i ); for ( int j = 0; j < i; j++ ) { print( " " + j ); } println( );}

Page 36: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

► Print out all 16 pairs of numbers from the set ► 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)

Page 37: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

How to Avoid Confusion with Nested Loops

►Focus on one loop at a time.►Abstract away the inner loop.

Page 38: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Printing a Shape

►Create a triangle pattern******

►Loop through rowsfor ( int i = 1; i <= n; i++ )

{ // make triangle row }

Page 39: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Printing a Shape (continued)

► The following loop creates a row of i starsfor ( int j = 1; j <= i; j++ ) r = r + "*";

r = r + "\n";

► Put loops together → Nested loopsString r = "" ;

for ( int i = 1; i <= n; i++ )

{

// make triangle row

}

Page 40: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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

}

Page 41: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

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

By the way, the built-in print methods calls the toString method automatically

Page 42: Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

►Create classes to print these shapes:* * * *

* * * ** * * ** * * *

* * * ** * ** **

* * * * * ** * * *

* * * * * * * * * *