Chapter 7 - IterationChapter GoalsControl StatementsWhile LoopsSlide 5Exampleif Flow Diagramwhile Flow DiagramSlide 9Compound BalanceSlide 11Slide 12Slide 13Infinite LoopsSlide 15Overflow ErrorUnderflow ErrorOff by One ErrorSlide 19do-while Statementsdo-while: Syntaxdo-while vs whileSlide 23do-while Flow DiagramSlide 25Slide 26Example: InputExample: while versionAvoid Repeat CodeSlide 30For LoopsFor Loops: Syntaxfor Flow DiagramSum ExampleSlide 35Interest ExampleSlide 37Slide 38Slide 39Slide 40Slide 41Slide 42Slide 43ScopeIs this legal?Nested LoopsMultiplication TablePracticeSlide 49Slide 50Counting LoopsSentinel LoopsSlide 53Loop and a halfTipsAlternatives to loop and a halfbreakCode JumpsSpaghetti CodeWhich loop to choose?Random NumbersSlide 62Slide 63Loop InvariantsChapter 7 - Chapter 7 - IterationIterationChapter GoalsChapter GoalsProgram repetiation statements – loops – Program repetiation statements – loops – with with forfor, , whilewhile, and , and do-whiledo-while statementsstatementsLearn potential pitfalls of infinite loops Learn potential pitfalls of infinite loops and off by one errorsand off by one errorsUnderstand nested loopsUnderstand nested loopsProcess inputProcess inputControl StatementsControl StatementsAlready learned about selection Already learned about selection statementsstatementsNow learn about Now learn about repetition repetition statements, statements, oror loop statements loop statementsRepetition 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 met3 types: 3 types: whilewhile, , do-whiledo-while, and , and forforWhile LoopsWhile LoopsWhileWhile statements/loops, repeat a body statements/loops, repeat a body of code until some condition is metof code until some condition is metThis 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 fullDrink beer until pitcher is doneDrink beer until pitcher is doneGet user input until they hit the Esc keyGet user input until they hit the Esc keyPlay a game until someone winsPlay a game until someone winsWhile LoopsWhile LoopsSyntax:Syntax:while ( <boolean expression> )while ( <boolean expression> )<statement> <statement> //AKA //AKA loop bodyloop bodySimilar 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 indeedNormally, it is a block statementNormally, it is a block statementKeeps executing the <statement> block Keeps executing the <statement> block as long as as long as <boolean expression><boolean expression> is is truetrueExampleExampleAdd 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 ////intializeintializewhile ( number <= 100 ) {while ( number <= 100 ) {//boolean expression//boolean expressionsum = sum + number;sum = sum + number;number++;number++;// what does this do?// what does this do?}}ifif Flow Diagram Flow Diagramconditionbodyfalsetruewhile while Flow DiagramFlow DiagramconditionbodyfalsetrueExampleExampleint bottlesOfBeer = 99int bottlesOfBeer = 99while (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”);}}Compound BalanceCompound BalanceProblem: 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 rateint 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.");While LoopsWhile Loopswhile (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 thisCan we stop it?Can we stop it?Infinite LoopsInfinite LoopsMost common mistake – loop is never Most common mistake – loop is never terminatedterminated<boolean expression> is always true<boolean expression> is always trueInfinite 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;}}Infinite LoopsInfinite LoopsCommon 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. decrementdecrementint 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;}}Overflow ErrorOverflow ErrorValue of a variable exceeds precisionValue of a variable exceeds precisionshort 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
View Full Document