chapter7

chapter7 - Chapter 7 Iteration Chapter Goals Program...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 7 Iteration Chapter Goals Program repetiation statements loops with for, while, and dowhile statements Learn potential pitfalls of infinite loops and off by one errors Understand nested loops Process input Control Statements Already learned about selection statements Now learn about repetition statements, or loop statements Repetition statements repeat a block of code for a fixed number of times, or until some condition is met 3 types: while, dowhile, and for While Loops While statements/loops, repeat a body of code until some condition is met This is helpful for certain problems such as: Feed cat until it is full Drink beer until pitcher is done Get user input until they hit the Esc key Play a game until someone wins While Loops Syntax: while ( <boolean expression> ) <statement> //AKA loop body Similar to if statements if the <statement> block is a single statement, curly braces are not indeed Normally, it is a block statement Keeps executing the <statement> block as long as <boolean expression> is true Example Add integers 1 through 100 (1+2+...+100) // Important to // intialize //boolean expression int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; number++; // what does this do? } if Flow Diagram true condition false body while Flow Diagram true condition false body Example int bottlesOfBeer = 99 while (bottlesOfBeer > 0){ System.out.println(bottlesOfBeer+" System.out.println(bottlesOfBeer+" on on the the wall"); wall"); bottlesOfBeer--; System.out.println("Take one down, pass it around); System.out.println(bottlesOfBeer+" on the wall"); } Compound Balance Problem: Want to calculate how many years my balance will take to appreciate to $20,000 given I start $10,000 and have a 5% interest rate int years = 0; Scanner in = new Scanner(System.in); System.out.print ("Enter target balance: "); int targetBalance = in.nextInt(); while (balance < targetBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println("Your target will be achieved in " + years + " years."); While Loops while (true){ <statement> } How long will this loop run? Why would we want to do this Can we stop it? Infinite Loops Most common mistake loop is never terminated <boolean expression> is always true Infinite loop have to close program (Ctrl+c) int count = 1; while (count != 10){ count += 2; } int product = 0; while (product < 500000){ product *= 5; } Infinite Loops Common cause not advancing variable int years = 0; while (years < 20){ double interest = balance * rate / 100; balance = balance + interest; } Common cause increment vs. decrement int years = 20; while (years > 0){ years++; double interest = balance * rate / 100; balance = balance + interest; } Overflow Error Value of a variable exceeds precision short s; while (s < 3000){ s++; } double count = 0; while (count != 1.0){ count = count + .333333333333333 } Underflow Error Real numbers are not always stored exactly, sometimes an approximation is needed double count = 0; while (count != 1.0){ count = count + 1.0/3.0; }//May not work! Off by One Error Another common error is to be off by one int count = 1; while (count < 10){ ... count++; } How many executions? int count = 0; while (count <= 10){ ... count++; } How many executions? Off by One Error Be careful when counting Analogous to logic problems If I place a post every ten feet, how many posts do I need for a 100 ft fence? dowhile Statements The second repetition statement: dowhile loop/statement while loops are use pretest format, where we test the boolean expression before executing anything dowhile is a posttest loop we test the boolean after executing the loop dowhile: Syntax do <single statement> while ( <boolean expression> ); OR do{ <statements> }while ( <boolean expression> ); dowhile vs while What does posttest vs. pretest mean? A while loop body is not guaranteed to execute while (false){...} dowhile body is guaranteed to execute at least once while Flow Diagram true condition false body dowhile Flow Diagram body condition true false Example int sum = 0, number = 1; do{ sum += number; number++; } while (sum <=1000000); //Sums all numbers 1 through 1,000,000 Example int count = 11; do { System.out.println(count); count = count + 1; } while (count < 5); Example: Input double value; do { System.out.println("Enter a positive number: "); value = in.nextInt(); } while (value <= 0); Example: while version Could use a flag boolean control variable double value; boolean done = false; while (!done) { System.out.println("Enter a positive number: "); value = in.nextInt(); if(value > 0) done = true; } count = 0; do { System.out.print("Enter score: "); score = in.nextInt(); count++; if (count >= 20) { System.out.println("Can't take more scores"); } else if (score < 0) { System.out.println("Invalid score"); } else if (score == 0) { System.out.println("User chooses to exit"); } } while ( !(count >= 20 || score == 0 || score < 0 ) Avoid Repeat Code count = 0; boolean repeat = true; do{ System.out.print("Enter score: "); score = in.nextInt(); count++; if (count >= 20){ System.out.println("Can't take any more scores"); repeat = false; } else if (score < 0){ System.out.println("Invalid score"); repeat = false; } else if (score == 0){ System.out.println("User chooses to exit"); repeat = false; } } while ( repeat )//Easier to understand For Loops Most common loop, mainly for count controlled loops for(i = start; i <= end; i++) { ... } For Loops: Syntax for (<initialization>; <boolean <single statement> OR for (<initialization>; <boolean <statements> } exp>; <update>) exp>; <update>){ Initialization occurs only the first time the loop is executed, boolean expression is tested before every loop The increment operator is applied at the end of each loop for Flow Diagram initialization false test condition true body increment Sum Example Saw this using while and dowhile, here we use a for loop int i, sum = 0; for (i = 1; i <=100; i++){ sum += i; //equivalent to sum = sum + 1; } i is a control variable, keeps track of number of repititions Interest Example for(int i = 1; i <= { double interest = balance = balance } n; i++) balance * rate/100; + interest; Sum Example int i, sum = 0; for (i = 1; i <=100; i++){ sum += i; //equivalent to sum = sum + 1; } i is set to 1 the first time the loop is executed Before executing each time, check to see that i<=100 (like in while loop) Add 1 to i at the end of each cycle Sum Example int sum = 0; for (int i = 1; i <=100; i++){ sum += i; //equivalent to sum = sum + 1; } We can also declare i in the initialization, but i will be local to the for loop and not available outside (scope!) Usually not an issue Can also leave initialization blank Sum Example int sum = 0; for (int i = 1; i <=100 && sum < 1111; i++){ sum += i; } Can test multiple conditions in boolean expression Is this still count controlled? Sum Example int sum = 0; for (int i = 1; i <=100 && sum < 1111; i += 2){ sum += i; //equivalent to sum = sum + 1; } Can have any formula for incrementing Add only odd integers Decrease by 1, i int sum = 0, i = 1; do{ sum += i; i++; } while ( i <= 100); int sum = 0, i = 1; while ( i <= 100 ){ sum += i; i++; } int i, sum = 0; for (i = 1; i <=100; i++){ sum += i; } For Loops For loops can have many formats that are legal for(int i =0; i <= 100; sum += i++); for(;;i++) { ... } for(System.out.println("Inputs: "); (x = in.nextDouble()) > 0; sum += x) count++; Scope Is this legal? for(int i = 0; i < 100; i++){ ... } System.out.println(i); What if you want to know the value of i after loop is done? Is this legal? for(int i = 0; i <= 10; i++) System.out.println(i * i); for(int i = 0; i <= 10; i++) System.out.println(i * i * i); -----------------for(int i = 0, j = 10; i <= 10; i++, j--) System.out.println(i * i * j); Nested Loops Recall from ifstatements, any type of statement can be placed in blocks In any loop, we can put an if statement, while loop, dowhile loop, for loop inside the body Very common to have another for loop inside a nestedfor statement Multiplication Table for (int i = 0; i <= 10; i++){ for (int j = 0; j <= 10; j++){ int result = i * j; System.out.print(" " + result); } System.out.println(""); } What will this output? What order will output in? How many times does each loop execute? Practice Write a loop to output the following pattern * * * * * * * * * * ... n rows Practice Do more code for the following * * * * * * * * * Given h, where h=3 above Practice Given N Calculate + 2/3 + +...+N1/N Counting Loops Add integers 1 through 100 (1+2+...+100) //Important to // intialize //boolean expression // what does this do? int sum = 0, number = 1; while ( number <= 100 ){ sum = sum + number; number++; } Count controlled the body is executed a fixed number of times Sentinelcontrolled loop executed repeatedly until a sentinel (designated value) is encountered Sentinel value: Can be used for indicating the end of a data set 0 or 1 make poor sentinels; better use a meaningful value (`Q' for quit) Sentinel Loops Sentinel Loops System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")) We are done else { double x = Double.parseDouble(input); . . . } How do we make this a loop? Loop and a half boolean done = false; while(!done){ System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")){ done = true; } else { double x = Double.parseDouble(input); . . . } } Tips Symmetric vs. Asymmetric for(int i = 1; i <= n; i++) for(int i = 0; i < str.length(); i++) Counting iterations for(int i = a; i <= b; i++) How many executions? Alternatives to loop and a half Can be confusing to read 2 alternatives: test input in condition, or use break while(!(input = in.next()).equalsIgnoreCase("Q")){ Process data } break boolean done = false; while(!done){ System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")){ break; } else { double x = Double.parseDouble(input); . . . } } Code Jumps break will immediately exit the loop, just like it does in a switch statement continue will skip the rest of the statements in the loop and starts the next iteration of the loop Spaghetti Code Many programmers avoid using these various jump statements break, continue, goto Can cause confusing code that often leads to harmful bugs Which loop to choose? Countcontrolled Loops for loops usually best Sentinelcontrolled Loops while loops usually beset What about dowhile? Priming reads, although can use a flag instead with while Random Numbers In a simulation, you repeatedly generate random numbers and use them to simulate an activity Random number generator Random generator = new Random(); int n = generator.nextInt(a); // 0 <= n < a double x = generator.nextDouble(); // 0 <= x < 1 Throw die (random number between 1 and 6) int d = 1 + generator.nextInt(6); Random Numbers If you use your program to produce a random sequence, remember that the sequence will be different every time Note: Not truly random (psuedorandom) Formula used, but uses complicated factors to make it seem random Random Numbers How do you use a random number generator to simulate the toss of a coin? How do we get a double between 0.0 and 5.0? 0.5 and 2.0? How do we choose a random coordinate on a grid? Loop invariant a condition that is always true (beginning, after each iteration, and at the end) Ex. Loop invariant: r*b = a i n Loop Invariants double r = 1, b = a; int i = n; while(i > 0){ if(i%2 == 0){ b = b*b; i = i-2; } else { r = r*b; i--; ...
View Full Document

Ask a homework question - tutors are online