1Chapter 7 Chapter 7 --IterationIterationChapter GoalsChapter GoalsProgram Program repitiationrepitiationstatements statements ––or loops or loops ––with the with the for, while, and dofor, while, and do--while statementswhile statementsLearn potential pitfalls of infinite loops and off by one Learn potential pitfalls of infinite loops and off by one errorserrorsUnderstand nested loopsUnderstand nested loopsProcess inputProcess inputChapter 7Chapter 7Control statementsControl statementsAlready learned about selection statementsAlready learned about selection statementsNow learn about Now learn about repetition statements, repetition statements, ororloop loop statementsstatementsRepetition statementsRepetition statements––repeat a block of code repeat a block of code for a fixed number of times, or until some for a fixed number of times, or until some condition is metcondition is met3 types: 3 types: whilewhile, , dodo--whilewhile, and , and forforWhile statementWhile statementWhileWhilestatements/loops, repeat a body of code statements/loops, repeat a body of code until some condition is metuntil some condition is metThis is helpful for certain problems such as:This is helpful for certain problems 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 statementWhile statementSyntax:Syntax:while ( <while ( <booleanbooleanexpression> )expression> )<statement> <statement> //AKA //AKA loop bodyloop bodySimilar to Similar to if statementsif statements––if the <statement> block if the <statement> block is a is a singlesinglestatement, curly braces are not indeedstatement, curly braces are not indeedNormally, it is a block statementNormally, it is a block statementKeeps executing the <statement> block as long Keeps executing the <statement> block as long as as <<booleanbooleanexpression>expression>is is truetrueExampleExampleAdd integers 1 through 100 (1+2+…+100)Add integers 1 through 100 (1+2+…+100)intintsum = 0, number = 1;sum = 0, number = 1;//Important to //Important to ////intializeintializewhile ( number <= 100 ){while ( number <= 100 ){////booleanbooleanexpressionexpressionsum = sum = sumsum+ number;+ number;number++;number++;// what does this do?// what does this do?}}2ififFlow DiagramFlow Diagramconditionbodyfalsetruewhile while Flow DiagramFlow DiagramconditionbodyfalsetrueExampleExampleintintbottlesOfBeerbottlesOfBeer= 99= 99while (while (bottlesOfBeerbottlesOfBeer> 0){> 0){System.out.println(bottlesOfBeerSystem.out.println(bottlesOfBeer+” on the wall”);+” on the wall”);System.out.println(bottlesOfBeerSystem.out.println(bottlesOfBeer+” on the wall”);+” on the wall”);bottlesOfBeerbottlesOfBeer----;;System.out.println(“TakeSystem.out.println(“Takeone down, pass it around);one down, pass it around);System.out.println(bottlesOfBeerSystem.out.println(bottlesOfBeer+” on the wall”);+” on the wall”);}}Compound BalanceCompound BalanceProblem: Want to calculate how many years my Problem: Want to calculate how many years my balance will take to appreciate to $20,000 given I balance will take to appreciate to $20,000 given I start $10,000 and have a 5% interest ratestart $10,000 and have a 5% interest rateintintyears = 0;years = 0;Scanner in = new Scanner in = new Scanner(System.inScanner(System.in););System.out.printSystem.out.print(“Enter target balance: “);(“Enter target balance: “);intinttargetBalancetargetBalance= = in.nextIntin.nextInt();();while (balance < while (balance < targetBalancetargetBalance)){{year++;year++;double interest = balance * rate / 100;double interest = balance * rate / 100;balance = balance = balancebalance+ interest;+ interest;}}System.out.println(“YourSystem.out.println(“Yourtarget will be target will be achieved in “+ years + “ years.”);achieved in “+ years + “ years.”);3while (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?Common Error 7.1Common Error 7.1Most common mistake Most common mistake ––loop is never loop is never terminatedterminated<<booleanbooleanexpression> is always trueexpression> is always trueInfinite loop Infinite loop ––have to close program (have to close program (Ctrl+cCtrl+c))intintcount = 1;count = 1;while (count != 10){while (count != 10){count += 2;count += 2;}}intintproduct = 0;product = 0;while (product < 500000){while (product < 500000){product *= 5;product *= 5;}}Infinite loopInfinite loopCommon cause Common cause ––not advancing variablenot advancing variableintintyears = 0;years = 0;while (years < 20){while (years < 20){double interest = balance * rate / 100;double interest = balance * rate / 100;balance = balance = balancebalance+ interest;+ interest;}}Common cause Common cause ––increment vs. decrementincrement vs. decrementintintyears = 20;years = 20;while (years > 0){while (years > 0){years++;years++;double interest = balance * rate / 100;double interest = balance * rate / 100;balance = balance = balancebalance+ interest;+ interest;}}OverflowOverflowValue 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 = countcount+ .333333333333333+ .333333333333333}}UnderflowUnderflowReal numbers are not always stored exactly, Real numbers are not always stored exactly, sometimes an approximation is neededsometimes an approximation is neededdouble count = 0;double count = 0;while (count != 1.0){while (count != 1.0){count = count = countcount+ 1.0/3.0;+ 1.0/3.0;}//May not work!}//May not work!Off by oneOff by oneAnother common error is to be off by oneAnother common error is to be off by oneintintcount = 1;count = 1;while (count < 10){while (count < 10){……count++;count++;}}How many executions?How many executions?intintcount = 0;count = 0;while (count <= 10){while (count <= 10){……count++;count++;}}How many executions?How many executions?4Off by
View Full Document