Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for,...

64
Chapter 7 - Chapter 7 - Iteration Iteration

Transcript of Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for,...

Page 1: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Chapter 7 - Chapter 7 - IterationIteration

Page 2: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Chapter GoalsChapter Goals Program repitiation statements – or loops Program repitiation statements – or loops

– with the for, while, and do-while – with the for, while, and do-while statementsstatements

Learn potential pitfalls of infinite loops Learn potential pitfalls of infinite loops and off by one errorsand off by one errors

Understand nested loopsUnderstand nested loops

Process inputProcess input

Page 3: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Chapter 7Chapter 7

Control statementsControl statements Already learned about selection Already learned about selection

statementsstatements Now learn about Now learn about repetition repetition

statements, statements, oror loop statements loop statements Repetition statementsRepetition statements – repeat a – repeat a

block of code for a fixed number of block of code for a fixed number of times, or until some condition is mettimes, or until some condition is met

3 types: 3 types: whilewhile, , do-whiledo-while, and , and forfor

Page 4: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

While statementWhile statement

WhileWhile statements/loops, repeat a body statements/loops, repeat a body of code until some condition is metof code until some condition is met

This is helpful for certain problems This is helpful for certain problems such as:such as: Feed cat until it is fullFeed cat until it is full Drink beer until pitcher is doneDrink beer until pitcher is done Get user input until they hit the Esc keyGet user input until they hit the Esc key Play a game until someone winsPlay a game until someone wins

Page 5: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

While statementWhile statementSyntax:Syntax:

while ( <boolean expression> )while ( <boolean expression> )<statement> <statement> //AKA //AKA loop bodyloop body

Similar to Similar to if statementsif statements – if the – if the <statement> block is a <statement> block is a singlesingle statement, curly braces are not indeedstatement, curly braces are not indeed

Normally, it is a block statementNormally, it is a block statement Keeps executing the <statement> Keeps executing the <statement>

block as long as block as long as <boolean expression><boolean expression> is is truetrue

Page 6: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

ExampleExample

Add integers 1 through 100 (1+2+…Add integers 1 through 100 (1+2+…+100)+100)

int sum = 0, number = 1;int sum = 0, number = 1; //Important to //Important to //// intializeintialize

while ( number <= 100 ){while ( number <= 100 ){ //boolean //boolean expressionexpression

sum = sum + number;sum = sum + number;

number++;number++; // what does this do?// what does this do?

}}

Page 7: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

ifif Flow Diagram Flow Diagram

condition

bodyfalse

true

Page 8: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

while while Flow DiagramFlow Diagram

condition

bodyfalse

true

Page 9: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

ExampleExampleint bottlesOfBeer = 99int bottlesOfBeer = 99

while (bottlesOfBeer > 0){while (bottlesOfBeer > 0){

System.out.println(bottlesOfBeer+” on the wall”);System.out.println(bottlesOfBeer+” on the wall”);

System.out.println(bottlesOfBeer+” on the wall”);System.out.println(bottlesOfBeer+” on the wall”);

bottlesOfBeer--;bottlesOfBeer--;

System.out.println(“Take one down, pass it around);System.out.println(“Take one down, pass it around);

System.out.println(bottlesOfBeer+” on the wall”);System.out.println(bottlesOfBeer+” on the wall”);

}}

Page 10: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Compound BalanceCompound Balance

Problem: Want to calculate how Problem: Want to calculate how many years my balance will take to many years my balance will take to appreciate to $20,000 given I start appreciate to $20,000 given I start $10,000 and have a 5% interest rate$10,000 and have a 5% interest rate

Page 11: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

int years = 0;int years = 0;

Scanner in = new Scanner(System.in);Scanner in = new Scanner(System.in);

System.out.print (“Enter target balance: “);System.out.print (“Enter target balance: “);

int targetBalance = in.nextInt();int targetBalance = in.nextInt();

while (balance < targetBalance)while (balance < targetBalance)

{{year++;year++;double interest = balance * rate / 100;double interest = balance * rate / 100;balance = balance + interest;balance = balance + interest;

}}

System.out.println(“Your target will be achieved System.out.println(“Your target will be achieved in “+ years + “ years.”);in “+ years + “ years.”);

Page 12: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Page 13: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

while (true){while (true){

<statement><statement>

}}

How long will this loop run?How long will this loop run?

Why would we want to do thisWhy would we want to do this

Can we stop it?Can we stop it?

Page 14: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Common Error 7.1Common Error 7.1 Most common mistake – loop is never Most common mistake – loop is never

terminatedterminated <boolean expression> is always true<boolean expression> is always true Infinite loop –Infinite loop – have to close program have to close program

(Ctrl+c)(Ctrl+c)int count = 1;int count = 1;

while (count != 10){while (count != 10){

count += 2;count += 2;

}}

int product = 0;int product = 0;

while (product < 500000){while (product < 500000){

product *= 5;product *= 5;

}}

Page 15: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Infinite loopInfinite loop

Common cause – not advancing variableCommon cause – not advancing variableint years = 0;int years = 0;while (years < 20){while (years < 20){

double interest = balance * rate / 100;double interest = balance * rate / 100;balance = balance + interest;balance = balance + interest;

}}

Common cause – increment vs. Common cause – increment vs. decrementdecrement

int years = 20;int years = 20;while (years > 0){while (years > 0){

years++;years++;double interest = balance * rate / 100;double interest = balance * rate / 100;balance = balance + interest;balance = balance + interest;

}}

Page 16: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

OverflowOverflow

Value of a variable exceeds precisionValue of a variable exceeds precision

short s;short s;

while (s < 3000){while (s < 3000){

s++;s++;

}}

double count = 0;double count = 0;

while (count != 1.0){while (count != 1.0){

count = count + .333333333333333count = count + .333333333333333

}}

Page 17: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

UnderflowUnderflow

Real numbers are not always stored Real numbers are not always stored exactly, sometimes an approximation exactly, sometimes an approximation is neededis needed

double count = 0;double count = 0;

while (count != 1.0){while (count != 1.0){

count = count + 1.0/3.0;count = count + 1.0/3.0;

}//May not work!}//May not work!

Page 18: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Off by oneOff by one Another common error is to be off by Another common error is to be off by

oneoneint count = 1;int count = 1;

while (count < 10){while (count < 10){

……

count++;count++;

}}

How many executions?How many executions?int count = 0;int count = 0;

while (count <= 10){while (count <= 10){

……

count++;count++;

}}

How many executions?How many executions?

Page 19: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Off by oneOff by one

Be careful when countingBe careful when counting

Analogous to logic problemsAnalogous to logic problems

If I place a post every ten feet, how If I place a post every ten feet, how many posts do I need for a 100 ft many posts do I need for a 100 ft fence?fence?

Page 20: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

do-while statementdo-while statement

The second repetition statement: The second repetition statement: do-do-while loop/statementwhile loop/statement

whilewhile loops are use loops are use pretest pretest format, format, where we test the boolean where we test the boolean expression before executing anythingexpression before executing anything

do-whiledo-while is a is a posttestposttest loop – we test loop – we test the boolean after executing the loopthe boolean after executing the loop

Page 21: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

SyntaxSyntax

dodo

<single statement><single statement>

whilewhile (( <boolean expression> <boolean expression> ))

OROR

dodo{{

<statements><statements>

}}whilewhile (( <boolean expression> <boolean expression> ))

Page 22: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Do-while vs whileDo-while vs while

What does this posttest vs. pretest What does this posttest vs. pretest meanmean

A while loop A while loop bodybody is not guaranteed to is not guaranteed to executeexecutewhile (false){…}while (false){…}

do-while body is guaranteed to execute do-while body is guaranteed to execute at leastat least once once

Page 23: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

while while Flow DiagramFlow Diagram

condition

bodyfalse

true

Page 24: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

dodo--while while Flow DiagramFlow Diagram

condition

body

true

false

Page 25: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

ExampleExample

int sum = 0, number = 1;int sum = 0, number = 1;

do{do{

sum += number;sum += number;

number++;number++;

} while (sum <=1000000);} while (sum <=1000000);

//Sums all numbers 1 through 1,000,000//Sums all numbers 1 through 1,000,000

Page 26: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

intint count = count = 1111;;

dodo {{System.out.println(count);System.out.println(count);count = count + 1;count = count + 1;

}} whilewhile ((count < 5count < 5););

Page 27: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

InputInput

double value;double value;

dodo{{

System.out.println(“Enter a positive number: “);System.out.println(“Enter a positive number: “);value = in.nextInt();value = in.nextInt();

}}while (value <= 0);while (value <= 0);

Page 28: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

While versionWhile version

Could use a flag – boolean control variableCould use a flag – boolean control variable

double value;double value;

boolean done = false;boolean done = false;

while (!done)while (!done)

{{

System.out.println(“Enter a positive number: “);System.out.println(“Enter a positive number: “);

value = in.nextInt();value = in.nextInt();

if(value > 0) done = true;if(value > 0) done = true;

}}

Page 29: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Avoid Repeat CodeAvoid Repeat Codecount = 0;count = 0;

do{do{

System.out.print(“Enter score: “);System.out.print(“Enter score: “);

score = in.nextInt();score = in.nextInt();

count++;count++;

if (if (count >= 20count >= 20){){

System.out.println(“Can’t take more scores”);System.out.println(“Can’t take more scores”);

} else if (} else if (score < 0score < 0){){

System.out.println(“Invalid score”);System.out.println(“Invalid score”);

} else if (} else if (score == 0score == 0){){

System.out.println(“User chooses to exit”);System.out.println(“User chooses to exit”);

}}

} while ( } while ( !(count >= 20 || score == 0 || score < 0 !(count >= 20 || score == 0 || score < 0 ))

Page 30: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

count = 0;count = 0;

boolean repeat = true;boolean repeat = true;

do{do{

System.out.print(“Enter score: “);System.out.print(“Enter score: “);

score = in.nextInt();score = in.nextInt();

count++;count++;

if (if (count >= 20count >= 20){){

System.out.println(“Can’t take any more System.out.println(“Can’t take any more scores”);scores”);

repeat = false;repeat = false;

} else if (} else if (score < 0score < 0){){

System.out.println(“Invalid score”);System.out.println(“Invalid score”);

repeat = false;repeat = false;

} else if (} else if (score == 0score == 0){){

System.out.println(“User chooses to exit”);System.out.println(“User chooses to exit”);

repeat = false;repeat = false;

}}

} while ( } while ( repeatrepeat )//Easier to understand)//Easier to understand

Page 31: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

7.2 for loop7.2 for loop

Most common loop, mainly for Most common loop, mainly for count-controlledcount-controlled loops loops

for(i = for(i = start; start; i <= i <= endend; i++); i++)

{{

......

}}

Page 32: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

SyntaxSyntax

for (for (<initialization><initialization>; ; <boolean exp><boolean exp>; ; <update><update>))

<single statement><single statement>

OROR

for (for (<initialization><initialization>;<;<boolean expboolean exp>; >; <update><update>){){

<statements><statements>

}}

Initialization occurs Initialization occurs onlyonly the first time the loop the first time the loop is executed, is executed,

boolean expression is tested boolean expression is tested beforebefore everyevery loop loop The increment operator is applied at the The increment operator is applied at the end end

of each loopof each loop

Page 33: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

forfor Flow DiagramFlow Diagram

test condition

body

true

false

increment

initialization

Page 34: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Sum problemSum problem

Saw it in Saw it in whilewhile and and do-while, do-while, here here it is in it is in forfor

intint i, sum = 0; i, sum = 0;

for (for (i = 1i = 1; ; i <=100i <=100; ; i++i++){){

sum += i; //equivalent to sum = sum + 1;sum += i; //equivalent to sum = sum + 1;

}}

i i is a is a control variablecontrol variable, keeps track , keeps track of number of repititionsof number of repititions

Page 35: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Page 36: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Interest ProblemInterest Problem

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

{{

double interest = balance * rate/100;double interest = balance * rate/100;

balance = balance + interest;balance = balance + interest;

}}

Page 37: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Page 38: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Sum problemSum problem

int i, sum = 0;int i, sum = 0;

for (for (i = 1i = 1; ; i <=100i <=100; ; i++i++){){

sum += i; //equivalent to sum = sum + 1;sum += i; //equivalent to sum = sum + 1;

}}

i is set to 1 the first time the loop is i is set to 1 the first time the loop is executedexecuted

Before executing each time, check to Before executing each time, check to see that i<=100 (like in while loop)see that i<=100 (like in while loop)

Add 1 to i at the end of each cycleAdd 1 to i at the end of each cycle

Page 39: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

InitializationInitialization

int int sum = 0;sum = 0;

for (for (int i = 1int i = 1; i <=100; i++){; i <=100; i++){

sum += i; //equivalent to sum = sum + 1;sum += i; //equivalent to sum = sum + 1;

}}

We can also declare We can also declare ii in the in the initialization, but initialization, but ii will be local to the will be local to the for loop and not available outsidefor loop and not available outside Usually not an issueUsually not an issue

Can also leave initialization blankCan also leave initialization blank

Page 40: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Boolean ExpressionBoolean Expression

int int sum = 0;sum = 0;

for (for (int i = 1; int i = 1; i <=100 && sum < 1111i <=100 && sum < 1111; i++){; i++){

sum += i; //equivalent to sum = sum + 1;sum += i; //equivalent to sum = sum + 1;

}}

Can test multiple Can test multiple conditionsconditions in in boolean expressionboolean expression Is this still count controlled?Is this still count controlled?

Page 41: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

UpdateUpdate

int int sum = 0;sum = 0;

for (for (int i = 1; i <=100 && sum < 1111; int i = 1; i <=100 && sum < 1111; i += 2i += 2){){sum += i; //equivalent to sum = sum + 1;sum += i; //equivalent to sum = sum + 1;

}}

Can have any formula for Can have any formula for incrementingincrementing Add only odd integersAdd only odd integers Decrease by 1, i--Decrease by 1, i--

Page 42: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

int sum = 0, number = 1;int sum = 0, number = 1;do{do{

sum += number;sum += number;number++;number++;

}while ( number <= 100)}while ( number <= 100)

int sum = 0, number = 1;int sum = 0, number = 1;while ( number <= 100 ){while ( number <= 100 ){

sum = sum + number;sum = sum + number;number++;number++;

}}

int i, sum = 0;int i, sum = 0;for (i = 1; i <=100; i++){for (i = 1; i <=100; i++){

sum += i; sum += i; }}

Page 43: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Legal for loopsLegal for loops

For loops can have many formats For loops can have many formats that are legalthat are legal

for(int i =0; i <= 100; sum += i++);for(int i =0; i <= 100; sum += i++);

for(;;i++){for(;;i++){

……

}}

for(System.out.println(“Inputs: “); (x = for(System.out.println(“Inputs: “); (x = in.nextDouble()) > 0; sum += x)in.nextDouble()) > 0; sum += x)

count++;count++;

Page 44: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

ScopeScope

Is this legal?Is this legal?

for(int i = 0; i < 100; i++){for(int i = 0; i < 100; i++){

……

}}

System.out.println(i);System.out.println(i);

What if you want to know the value of What if you want to know the value of i after loop is donei after loop is done

Page 45: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Is this legal?Is this legal?

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

System.out.println(i * i);System.out.println(i * i);

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

System.out.println(i * i * i);System.out.println(i * i * i);

------------------------------------

for(int i = 0, j = 10; i <= 10; i++, j--)for(int i = 0, j = 10; i <= 10; i++, j--)

System.out.println(i * i * i);System.out.println(i * i * i);

Page 46: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

7.4 Nested loops7.4 Nested loops

Recall from Recall from if-statementsif-statements, any type of , any type of statement can be placed in the blocks statement can be placed in the blocks or bodyor body

In In forfor loops, we can put an if loops, we can put an if statement, while loop, do-while loop, statement, while loop, do-while loop, etc. inside the bodyetc. inside the body

Very common to have another for loop Very common to have another for loop inside – a inside – a nested-for statementnested-for statement

Page 47: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Mult. TableMult. Table

for (int i = 0; i <= 10; i++){for (int i = 0; i <= 10; i++){

for (int j = 0; j <= 10; j++){for (int j = 0; j <= 10; j++){

result = i * j;result = i * j;

System.out.print(“ “ + result);System.out.print(“ “ + result);

}}

System.out.println(“”);System.out.println(“”);

}} What will this output?What will this output? What order will output in?What order will output in? How many times does each loop execute?How many times does each loop execute?

Page 48: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

PracticePractice

Write a loop to output the following Write a loop to output the following patternpattern**

* ** *

* * ** * *

* * * ** * * *

……

n rowsn rows

Page 49: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

PracticePractice

Do more code for the followingDo more code for the following

**

* ** *

* * ** * *

* ** *

**

Given h, where h=3 aboveGiven h, where h=3 above

Page 50: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

PracticePractice

Given NGiven N

Calculate ½ + 2/3 + ¾ +…+N-1/NCalculate ½ + 2/3 + ¾ +…+N-1/N

Page 51: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

7.4 Sentinel Values7.4 Sentinel Values

Add integers 1 through 100 (1+2+…Add integers 1 through 100 (1+2+…+100)+100)

int sum = 0, number = 1;int sum = 0, number = 1; //Important to //Important to //// intializeintialize

while ( number <= 100 ){while ( number <= 100 ){ //boolean expression//boolean expression

sum = sum + number;sum = sum + number;

number++;number++; // what does this do?// what does this do?

}}

Count controlled Count controlled – the body is executed – the body is executed a fixed number of timesa fixed number of times

Page 52: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Sentinel-controlled loopSentinel-controlled loop – – executed repeatedly until a executed repeatedly until a sentinelsentinel(designated value) is (designated value) is encounteredencountered

Sentinel valueSentinel value: Can be used for : Can be used for indicating the end of a data set indicating the end of a data set

0 or -1 make poor sentinels; better 0 or -1 make poor sentinels; better use a meaningful value (‘Q’ for quit)use a meaningful value (‘Q’ for quit)

Page 53: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

System.out.print("Enter value, Q to quit: ");System.out.print("Enter value, Q to quit: ");String input = in.next();String input = in.next();

if (input.equalsIgnoreCase("Q"))if (input.equalsIgnoreCase("Q"))We are doneWe are done

else { else { double x = Double.parseDouble(input); double x = Double.parseDouble(input); . . . . . .

}}

How do we make this a loop?How do we make this a loop?

Page 54: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Loop and a halfLoop and a half

boolean done = false;boolean done = false;

while(!done){while(!done){

System.out.print("Enter value, Q to quit: ");System.out.print("Enter value, Q to quit: ");

String input = in.next();String input = in.next();

if (input.equalsIgnoreCase("Q")){if (input.equalsIgnoreCase("Q")){done = true;done = true;

} else { } else {

double x = Double.parseDouble(input); double x = Double.parseDouble(input);

. . . . . .

}}

}}

Page 55: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

TipsTips

Symmetric vs. AsymmetricSymmetric vs. Asymmetricfor(int i = 1; i <= n; i++)for(int i = 1; i <= n; i++)

for(int i = 0; i < str.length(); i++)for(int i = 0; i < str.length(); i++)

Counting iterationsCounting iterationsfor(int i = a; i <= b; i++)for(int i = a; i <= b; i++)

How many executions?How many executions?

Page 56: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Alternatives to loop and Alternatives to loop and a halfa half

Can be confusing to readCan be confusing to read 2 alternatives: test input in 2 alternatives: test input in

condition, or use breakcondition, or use break

while(!(input = while(!(input = in.next()).equalsIgnoreCase(“Q”)){in.next()).equalsIgnoreCase(“Q”)){

Process dataProcess data

}}

Page 57: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

breakbreak

boolean done = false;boolean done = false;while(!done){while(!done){

System.out.print("Enter value, Q to quit: ");System.out.print("Enter value, Q to quit: ");String input = in.next();String input = in.next();

if (input.equalsIgnoreCase("Q")){if (input.equalsIgnoreCase("Q")){break;break;

} else { } else { double x = Double.parseDouble(input); double x = Double.parseDouble(input); . . . . . .

}}}}

Page 58: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Code jumpsCode jumps

breakbreak – exits loop – exits loop Will immediately exit, just like for Will immediately exit, just like for

switchswitch

continuecontinue – will skip the rest of the – will skip the rest of the statements in the loop and start next statements in the loop and start next iteration of the loopiteration of the loop

Page 59: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Spaghetti CodeSpaghetti Code

Many programmers avoid using Many programmers avoid using these various jump statementsthese various jump statements break, continue, gotobreak, continue, goto

Can cause confusing code that often Can cause confusing code that often leads to harmful bugsleads to harmful bugs

Page 60: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Which to choose?Which to choose?

Count controlledCount controlled for loops usually bestfor loops usually best

Sentinel based loopsSentinel based loops while loops usually besetwhile loops usually beset

What about do-while?What about do-while? Priming reads, although can use a flag Priming reads, although can use a flag

instead withinstead with while while

Page 61: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

7.5 Random Numbers7.5 Random Numbers

In a simulation, you repeatedly generate In a simulation, you repeatedly generate random numbers and use them to simulate random numbers and use them to simulate an activity an activity

Random number generatorRandom number generatorRandom generator = new Random();Random generator = new Random();int n = generator.nextInt(a); // 0 <= n < aint n = generator.nextInt(a); // 0 <= n < adouble x = generator.nextDouble(); // 0 <= x < 1double x = generator.nextDouble(); // 0 <= x < 1

Throw die (random number between 1 and Throw die (random number between 1 and 6)6)int d = 1 + generator.nextInt(6);int d = 1 + generator.nextInt(6);

Page 62: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

SequenceSequence

If producing a random sequence, the If producing a random sequence, the sequence will be different every timesequence will be different every time

Note: Not truly random Note: Not truly random (psuedorandom)(psuedorandom) Formula used, but uses complicated Formula used, but uses complicated

factors to make it seem Randomfactors to make it seem Random

Page 63: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

How do you use a random number How do you use a random number generator to simulate the toss of a generator to simulate the toss of a coin? coin?

How do we get a double between 0.0 How do we get a double between 0.0 and 5.0? 0.5 and 2.0?and 5.0? 0.5 and 2.0?

How do we choose a random How do we choose a random coordinate on a grid?coordinate on a grid?

Page 64: Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Loop InvariantLoop Invariant Loop invariant – a condition that is Loop invariant – a condition that is

always true (beginning, after each always true (beginning, after each iteration, and at the end)iteration, and at the end)

Ex. Loop invariant: Ex. Loop invariant: r*br*bi i = a= ann

double r = 1, b = a;double r = 1, b = a;

int i = n;int i = n;

while(i > 0){while(i > 0){

if(i%2 == 0){if(i%2 == 0){

b = b*b;b = b*b;

i = i-2;i = i-2;

} else {} else {

r = r*b;r = r*b;

i--;i--;

}}

}}