DOC PREVIEW
UW-Madison CS 302 - Chapter 7 - Iteration

This preview shows page 1-2-3-4 out of 11 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Chapter 7 Chapter 7 --IterationIterationChapter GoalsChapter GoalsProgram Program repitiationrepitiationstatements statements ––or loops or loops ––with the with the for, while, and dofor, while, and do--while statementswhile statementsLearn potential pitfalls of infinite loops and off by one Learn potential pitfalls of infinite loops and off by one errorserrorsUnderstand nested loopsUnderstand nested loopsProcess inputProcess inputChapter 7Chapter 7Control statementsControl statementsAlready learned about selection statementsAlready learned about selection statementsNow learn about Now learn about repetition statements, repetition statements, ororloop loop statementsstatementsRepetition 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 met3 types: 3 types: whilewhile, , dodo--whilewhile, and , and forforWhile statementWhile statementWhileWhilestatements/loops, repeat a body of code statements/loops, repeat a body of code until some condition is metuntil some condition is metThis 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 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 winsWhile statementWhile statementSyntax:Syntax:while ( <while ( <booleanbooleanexpression> )expression> )<statement> <statement> //AKA //AKA loop bodyloop bodySimilar 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 indeedNormally, it is a block statementNormally, it is a block statementKeeps executing the <statement> block as long Keeps executing the <statement> block as long as as <<booleanbooleanexpression>expression>is is truetrueExampleExampleAdd 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 BalanceProblem: 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 thisCan we stop it?Can we stop it?Common Error 7.1Common Error 7.1Most common mistake Most common mistake ––loop is never loop is never terminatedterminated<<booleanbooleanexpression> is always trueexpression> is always trueInfinite 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 loopCommon 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;}}OverflowOverflowValue 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}}UnderflowUnderflowReal 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 oneAnother 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

UW-Madison CS 302 - Chapter 7 - Iteration

Download Chapter 7 - Iteration
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Chapter 7 - Iteration and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Chapter 7 - Iteration 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?