Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy Numerical Analysis Copyright 1999, James M. Slack Loops: Introduction Loop Group of statements the computer executes over and over, as long as some criterion holds Statement Statement Three loop statements in Java for while do-while Statement Statement Programming and Problem Solving With Java 2 Loops: Introduction Many real-world activities involve loops Example: Library checkout Clear up patron's overdue materials and outstanding fines, if any. Scan or type patron's ID number. Update ID if not current and valid. Scan material code for each item. Stamp due date on each item. Give materials and library card back to the patron. Checkout librarian does these steps until library closes Programming and Problem Solving With Java 3 Loops: Kinds Two kinds of loops Counting Event-controlled Counting loop Computer knows, when it begins the loop, how many times to execute the body Counting loop statement in Java: for Event-controlled Computer stops the loop when a condition is no longer true Event-controlled loop statements in Java: while, do-while Programming and Problem Solving With Java 4 Loops: Kinds Counting loops are subset of event-controlled "Event" of counting loop: counting variable reaches the limit Event-controlled loops Counting loops Programming and Problem Solving With Java 5 Flow of control The for Statement initalization part The counting loop statement in Java Example Initialization Condition Is condition true? Increment No for (int count = 1; count <= 5; count++) { System.out.println(count); } Output 1 2 3 4 5 Programming and Problem Solving With Java Yes for-body increment part Next statement in program 6 The for Statement: Example Sum the first 20 integers Flow of control int number = 1 int total = 0; for (int number = 1; number <= 20; number++) { total = total + number; } System.out.println("1 + 2 + ... + 20 is " + total); Output Is number <= 20? No Yes total = total + number 1 + 2 + ... + 20 is 210 number++ Next statement in program Programming and Problem Solving With Java 7 The for Statement: Example Flow of control initalization part What does this display? for (int count = 10; count <= 6; count++) { System.out.println(count); } Is condition true? No Yes for-body increment part Next statement in program Programming and Problem Solving With Java 8 The for Statement: Syntax Can leave out initialization, condition, or increment int total = 0, number = 1; for (; number <= 20;) { total = total + number; number++; } System.out.println("1 + 2 + ... + 20 is " + total); Don't need to use same variable throughout int y = 10; for (int x = 0; x < y; y--) { System.out.println(x + " " + y); } (Confusing!) Programming and Problem Solving With Java 9 The for Statement: Draw Circles Example: drawing circles in turtle graphics Can simulate circles with drawPolygon() Too many sides makes drawing too slow 20 to 40 sides looks ok Programming and Problem Solving With Java 360 sides 4.2 seconds 180 sides 1.9 seconds 90 sides 0.9 seconds 45 sides 0.4 seconds 20 sides 0.2 seconds 10 sides 0.1 seconds 10 The for Statement: drawPolygon() The drawPolygon() method (Chapter 2) // drawPolygon: Draws a regular polygon with the given // number of sides, and all sides are of // length size void drawPolygon(int numSides, int size) throws TurtleException { for (int side = 1; side <= numSides; side++) { this.move(size); this.turnRight(360 / numSides); } } Programming and Problem Solving With Java 11 The for Statement: drawPolygon() Drawing circles with drawPolygon() How to draw circle with specific radius? Circumference of a circle 2 x x radius Distance around a polygon sides x size Set these equal to each other, solve for size 2 x x radius = sides x size size = (2 x x radius) / sides In Java int size = (int) Math.round(2 * Math.PI * radius) / NUM_SIDES; Programming and Problem Solving With Java 12 The for Statement: drawCircle() Drawing circles with drawPolygon() First version of drawCircle() // drawCircle: (First version) Draws a circle of the given // radius, to the right of the turtle. The turtle // finishes at the same position and direction as // before. The pen must be down beforehand, and is // down afterward. static final int NUM_SIDES = 20; // Must divide into 360 public void drawCircle(int radius) throws TurtleException { int size = (int) Math.round(2 * Math.PI * radius) / NUM_SIDES; this.drawPolygon(NUM_SIDES, size); } Computes size of 20-sided polygon to achieve desired radius Programming and Problem Solving With Java 13 The for Statement: drawCircle() Test drawCircle() // This program draws a circle inside a square, // to see how accurate the circle drawing method is import turtlegraphics.*; import SmartTurtle; public class TestCircle { static final int CIRCLE_SIZE = 300; Oops! public static void main[] (String args) throws TurtleException { SmartTurtle myTurtle = new SmartTurtle(); } } myTurtle.goLeft(200); myTurtle.turnAround(); myTurtle.move(CIRCLE_SIZE); myTurtle.turnAround(); myTurtle.drawSquare(CIRCLE_SIZE * 2); myTurtle.move(CIRCLE_SIZE); myTurtle.drawCircle(CIRCLE_SIZE); Programming and Problem Solving With Java 14 The for Statement: drawCircle() What's wrong with drawCircle()? Turtle draws first side of polygon straight up Turtle draws last side of polygon at an angle Need to balance these two angles At beginning First edge of polygon Turtle's starting position this.turnRight(360 / NUM_SIDES / 2); At end Last edge of polygon this.turnLeft(360 / NUM_SIDES / 2); Programming and Problem Solving With Java 15 The for Statement: drawCircle() Final version of drawCircle() // drawCircle: (Final version) Draws a circle of the given // radius, to the right of the turtle. The turtle // finishes at the same position and direction as // before. The pen must be down beforehand, and is // down afterward. static final int NUM_SIDES = 20; // must divide into 360 // with an even quotient public void drawCircle(int radius) throws TurtleException { this.turnRight(360 / NUM_SIDES / 2); int size = (int) Math.round(2 * Math.PI * radius) / NUM_SIDES; this.drawPolygon(NUM_SIDES, size); this.turnLeft(360 / NUM_SIDES / 2); } Ah... New restriction: number of sides must divide into 360 with even quotient (So can divide this by 2 for start and end angles) Programming and Problem Solving With Java 16 The while Statement Flow of control One of two event-controlled loop statements Is condition true? Body keeps executing as long as condition is true Example int i = 0; while (i < 3) { System.out.println(i); i++; } No Yes while-body Output 0 1 2 Programming and Problem Solving With Java Next statement in program 17 The while Statement while similar to if statement while statement if statement while (i < 3) { System.out.println(i); i++; } while statement Yes Flow of control Is condition true? Is condition true? No if statement Flow of control No Yes if-body while-body Next statement in program Next statement in program if (i < 3) { System.out.println(i); i++; } Programming and Problem Solving With Java 18 The while Statement: Sentinels Sentinel loop Sentinel: not data, but marks the end of data Sentinel loop: reads data values until sentinel Example Sum series of numbers terminated by zero 10, 20, 30, 0 Data values Programming and Problem Solving With Java Sentinel 19 The while Statement: Sentinels Sentinel loop example int sum = 0, number; number = Keyboard.readInt("Enter first number: "); while (number != 0) { sum = sum + number; number = Keyboard.readInt("Enter next number: "); } System.out.println("The sum is " + sum); Enter first number: 10 Enter next number: 20 Enter next number: 30 Enter next number: 0 The sum is 60 Trace Statement number sum int sum = 0, number; number = Keyboard.readInt("Enter first number (0 to stop): )"); while (number != 0) sum = sum + number; number = Keyboard.readInt("Enter next number (0 to stop): )"); while (number != 0) sum = sum + number; number = Keyboard.readInt("Enter next number (0 to stop): )"); while (number != 0) sum = sum + number; number = Keyboard.readInt("Enter next number (0 to stop): )"); while (number != 0) System.out.println("The sum is " + sum); — 10 10 10 20 10 10 30 30 30 0 0 0 0 0 0 10 10 10 30 30 30 60 60 60 60 Programming and Problem Solving With Java 20 The while Statement: Infinite Loop Infinite loop Loop that doesn't stop Easy to write accidentally with while statement Infinite loop example 1 while (x < 3) { y++; } Infinite loop example 2 sum = 0; count = 0; while (count < 100) { sum = sum + count; } System.out.println("Sum of numbers from 1 to 100 is " + sum); Programming and Problem Solving With Java 21 The while Statement: Infinite Loop Infinite loop example 3 answer = Keyboard.readChar("Say hi? (y/n)"); while (answer == 'y') System.out.println("Hi!"); answer = Keyboard.readChar("Say hi? (y/n)"); System.out.println("Bye!"); Infinite loop example 3 int x = 0; while (x < 10); { System.out.println(x); x++; } Programming and Problem Solving With Java 22 The while Statement: Infinite Loop Why doesn't compiler catch infinite loops? Halting problem: Impossible for a computer program to detect all possible infinite loops in another program Up to the programmer to avoid infinite loops When you write a while statement Make sure some statement in the while-body makes the condition false Programming and Problem Solving With Java 23 The while Statement: Menus Example: Writing menu-based programs Menu: List of selections that user can pick from Writing a text-based menu system with while Present menu Get selection from user As long as not quit •Do the selection •Present the menu •Get next selection Programming and Problem Solving With Java File Edit View Flip Window Help New Open Save Save As Exit Drawing 24 The while Statement: Menus Skeleton for text-based menu // Present the menu the first time // Get first selection from user while (selection != quitOption) { // Do selection // Present the menu again // Get next selection from user } Menu 0. 1. 2. 3. Quit Enter beginning balance Enter interest rate Compute ending balance Example: Compute bank balance --- Bank Balance Menu --0. Quit 1. Enter beginning balance 2. Enter interest rate 3. Compute ending balance Enter selection (0, 1, 2, or 3): _ Programming and Problem Solving With Java 25 The while Statement: Menus Bank Balance Program Present menu Get selection from user As long as not quit •Do the selection •Present the menu •Get next selection int selection; double balance = 0.00; double rate = 0.00; // Display program title System.out.println("--- Compute End-of-Year Bank Balance ---"); System.out.println(); // Display menu, get first selection System.out.println("--- Bank Balance Menu ---"); System.out.println("0. Quit"); System.out.println("1. Enter beginning balance"); System.out.println("2. Enter interest rate"); System.out.println("3. Compute ending balance"); selection = Keyboard.readInt("Enter selection (0, 1, 2, or 3): ", 0, 3); Programming and Problem Solving With Java 26 The while Statement: Menus // Handle the first selection; keep handling selections until // user picks the quit selection (0) while (selection != 0) { switch (selection) { case 1: balance = Keyboard.readDouble("Enter beginning balance: "); break; case 2: rate = Keyboard.readDouble("Enter interest rate: "); break; case 3: System.out.println("Ending balance is " + (balance + balance * rate)); break; default: System.out.println("Problem with switch statement"); break; } } // Display menu, get next selection System.out.println(); System.out.println("--- Bank Balance Menu ---"); System.out.println("0. Quit"); System.out.println("1. Enter beginning balance"); System.out.println("2. Enter interest rate"); System.out.println("3. Compute ending balance"); selection = Keyboard.readInt("Enter selection (0, 1, 2, or 3): ", 0, 3); System.out.println("Bye!"); Programming and Problem Solving With Java 27 The while Statement: Counting Writing counting loops with while Can convert for statement to while for (initialization ; condition; increment) { for-body } initialization; while (condition) { for-body; increment; } int total = 0; int number = 1, total = 0; for (int number = 1; number <= 20; number++) { total = total + number; } while (number <= 20) { total = total + number; number++; } Programming and Problem Solving With Java 28 Kinds of Loops Condition at the top Flow of control Condition at the bottom Flow of control Condition in the middle body (begin) body Yes condition Flow of control condition condition Yes Yes No No No body (end) statement statement body statement Programming and Problem Solving With Java 29 Kinds of Loops Condition at the top Condition tested before the body Java statements: for and while Condition at the bottom Condition tested after the body Java statements: do-while Condition in the middle Condition tested inside the body No built-in Java statement Programming and Problem Solving With Java 30 The do-while Statement The "other" event-controlled loop statement Body keeps executing as long as condition is true Flow of control do-while-body Example int i = 0; do { System.out.println(i); i++; } while (i < 3); Output 0 1 2 Programming and Problem Solving With Java Yes Is condition true? No Next statement in program 31 The do-while Statement Difference from while statement do-while executes body at least once while statement may not execute body at all Example while int i = 10; while (i < 3) { System.out.println(i); i++; } do-while int i = 10; do { System.out.println(i); i++; } while (i < 3); Output (nothing) Programming and Problem Solving With Java 10 32 The do-while Statement: Format Poor style do { do-while-body } while (condition); Looks like the beginning of a while statement Programming and Problem Solving With Java Preferred style do { do-while-body } while (condition); The brace before while distinguishes it as part of a do-while 33 The do-while Statement: Example Program to help children learn multiplication int guessNum = 0, response; System.out.println("What is " + operand2 do { guessNum++; response = Keyboard.readInt("Enter } while (response != operand1 + operand1 + " times " + "?"); guess number " + guessNum + ": "); * operand2); System.out.println("Correct!"); Equivalent while statement requires two copies of body One before loop starts One inside the loop Programming and Problem Solving With Java 34 Numerical Accuracy // Add up 0.10 until the sum is 1.0 (Wrong) public class AddTo1 { public static void main(String[] args) { double total = 0.0; } } while (total != 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done"); Total Total Total Total Total Total Total Total Total Total Total Total Total Total Programming and Problem Solving With Java so so so so so so so so so so so so so so far: far: far: far: far: far: far: far: far: far: far: far: far: far: 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 1.0999999999999999 1.2 1.3 1.4000000000000001 35 Numerical Accuracy: Round-off 0.1+0.1+0.1+ 0.1+0.1+0.1+0.1+0.1+0.1+0.1 1.0? Round-off error Can happen only with floating-point arithmetic Computer stores numbers in binary, not base 10 Representable number: can store in finite number of digits Unrepresentable in base 10: Representable in base 10: 1/3 = 0.333333333... 1/4 = 0.25 Some representable numbers in base 10 are unrepresentable in binary 0.10 (decimal) = 0.00011001100110011001100 . . . (binary) Can only store approximation of 0.10 Programming and Problem Solving With Java 36 Numerical Accuracy: Round-off Round-off error can happen with representable numbers Example: 1.3707275390625 (decimal) = 1.0101111011101 (binary) Suppose computer can only store 8 binary digits Binary Decimal 1.0101111011101 1.3707275390625 1.0101111 1.3671875 0.0000000011101 0.0035400390625 Computer's version of number is an approximation Programming and Problem Solving With Java 37 Numerical Accuracy: Comparisons Don’t compare floating-point numbers with == or != double total = 0.0; while (total != 1.0) ... Instead: // Avoid Use integers int total = 0; while (total != 10) ... // Use 1 for 1/10 Use <=, >=, <, or > double total = 0.0; while (total <= 1.0) ... // Good approach Check if numbers are very close double total = 0.0; // Can set exact tolerance while (Math.abs(total - 1.0) > 0.00001) ... Programming and Problem Solving With Java 38 Numerical Accuracy: Arithmetic Avoid arithmetic on floating-point numbers that are very different in size Simulate space probe from earth to Proxima Centauri double centimetersToProximaCentauri = 4067815793829482158.0; while (centimetersToProximaCentauri > 0.0) { // Simulate action of space probe here ... centimetersToProximaCentauri = centimetersToProximaCentauri - 1.0; } This loop is infinite: computer stores 4067815793829482158.0 as 4067815793829482000.0 4067815793829482000.0 - 1.0 4067815793829482000.0 One solution: use kilometers instead Programming and Problem Solving With Java 39 Condition-in-the-Middle Loops Hypothetical condition-in-the-middle loop (not Java) loop { number = Keyboard.readInt("Number (0 to stop): "); until (number == 0); sum = sum + number; } Can use as while or do-while Move until up for while, down for do-while Equivalent while loop number = Keyboard.readInt("Enter first number (0 to stop): "); while (number != 0) { sum = sum + number; number = Keyboard.readInt("Enter next number (0 to stop): "); } Must duplicate part of body before loop starts Programming and Problem Solving With Java 40 Condition-in-the-Middle Loops Can use break statement to stop loop early Put "if (condition) break" in infinite loop while (true) { number = Keyboard.readInt("Number (0 to stop): "); if (number == 0) break; sum = sum + number; } System.out.println("Sum is " + sum); Doesn't work if break is inside switch Must label the loop statement loop: while (true) { switch (...) { case xx: break loop; ... Programming and Problem Solving With Java 41 The continue Statement Syntax continue; or continue label; Example for (i = 0; i < 100; i++) { if (i % 2 == 0) // Ignore even numbers { continue; } System.out.println(i); } Action Control skips rest of loop iteration; starts next iteration for loop: computer executes the increment part before starting next iteration Programming and Problem Solving With Java 42 Numerical Analysis Study of use of arithmetic in computer programs Some issues in numerical analysis Minimize round-off errors Solve problems that don't have exact solution (or exact solution is difficult to find) Finding roots of mathematical functions Root of function: Value of x that makes function 0 Often difficult to find roots algebraically Example: find all roots of f(x) = x5 - 5x + 1 Programming and Problem Solving With Java 43 Numerical Analysis: Roots Find roots of f(x) = x5 - 5x + 1 Plot the function 30 20 10 f(x) 0 -10 -20 -30 -2 -1 0 1 2 x Three roots: one is between -1 and -2 Programming and Problem Solving With Java 44 Numerical Analysis: Bisection Use bisection to find root of f(x) = x5 - 5x + 1 Plot shows a root between -1 and -2 Pick 2 values of x, one on either side of root x value f(x) value Above zero -1 -1.5 5 0.90625 Zero value ??? 0 Below zero -2 -21 Use -1.5 as approximation of root, plug into function f (1.5) (1.5)5 5(1.5) 1 7.59375 7.5 1 0.90625 0.90625 > 0, so it replaces old "above 0" value Programming and Problem Solving With Java 45 Numerical Analysis: Bisection Use bisection to find root of f(x) = x5 - 5x + 1 Next evaluate f(x) at -1.75 (halfway between -1.5 and -2) x value f(x) value Above zero -1.5 0.90625 Zero value ??? 0 Below zero -2 -1.75 -21-6.66301 f(-1.75) is -6.66301 -6.66301 < 0, so it replaces old "below 0" value Programming and Problem Solving With Java 46 Numerical Analysis: Bisection Keep using bisection to get as close to 0 as desired Each iteration cuts range by half 2 1 0 -1 Upper -2 Lower -3 Midpoint -4 f(Midpoint) -5 -6 -7 -8 0 1 2 3 4 5 6 7 8 9 10 11 12 Iterations Programming and Problem Solving With Java 47 Numerical Analysis: Bisection Bisection advantages Bisection disadvantages Simple and effective Little or no round-off error Slow Only finds one root at a time Can't tell if function has other roots Appropriate for continuous intervals only 2 1.5 1 0.5 f(x) 0 -0.5 Noncontinuous function -1 -1.5 -2 -1 -0.5 0 0.5 1 x Programming and Problem Solving With Java 48 Numerical Analysis: Bisection Bisection Program // // // // // // // // Find zero of a function by bisection. Displays bound1, bound2, midpoint between bound1 and bound2, and f(midpoint). If f(midpoint) is not within +/- ERROR, cuts area in half and repeats. NOte: Required that f(bound2) < 0 < f(bound1), and there exists f(x) such that f(x) == 0, x is between bound1 and bound2, and f() is continuous between f(bound1) and f(bound2) import Keyboard; import Format; public class Bisection { static final double ERROR = 0.001; // Maximum difference between // generated solution and zero static final int WIDTH = 14; static final int DECIMALS = 5; // Width of output numbers // Decimals of output numbers // evaluateFunction: Returns f(x) (Put your function here) static double evaluateFunction(double x) { return Math.pow(x, 5) - (5 * x) + 1; } Programming and Problem Solving With Java 49 Numerical Analysis: Bisection public static void main(String[] args) throws java.io.IOException { double bound1, bound2; System.out.println("--- Find Zeros of a Function " + "by Bisection ---"); System.out.println(); // Get initial bounds for the value of x from the user System.out.println("Enter two values that surround the value"); System.out.println("of x that makes the function 0."); bound1 = Keyboard.readDouble("Value of x that gives " + "positive value " + "from function: "); bound2 = Keyboard.readDouble("Value of x that gives " + "negative value " + "from function: "); System.out.println(); double midpoint; System.out.println(Format.padRight("Bound1", WIDTH) + Format.padRight("Bound2", WIDTH) + Format.padRight("Midpoint", WIDTH) + Format.padRight("f(Midpoint)", WIDTH)); System.out.println(); Programming and Problem Solving With Java 50 Numerical Analysis: Bisection // Do first cut before the loop midpoint = (bound1 + bound2) / 2; System.out.println(Format.pad(bound1, WIDTH, DECIMALS) + Format.pad(bound2, WIDTH, DECIMALS) + Format.pad(midpoint, WIDTH, DECIMALS) + Format.pad(evaluateFunction(midpoint), WIDTH, DECIMALS)); } } // Keep reducing the area between the bounds until the // f(midpoint) is within ERROR tolerance of 0.0 while (Math.abs(evaluateFunction(midpoint)) > ERROR) { if (evaluateFunction(midpoint) > 0.0) bound1 = midpoint; else bound2 = midpoint; midpoint = (bound1 + bound2) / 2; System.out.println(Format.pad(bound1, WIDTH, DECIMALS) + Format.pad(bound2, WIDTH, DECIMALS) + Format.pad(midpoint, WIDTH, DECIMALS) + Format.pad(evaluateFunction(midpoint), WIDTH, DECIMALS)); } Program uses Format.pad() (from Chapter 7) Format.pad(floating-point-number, width, decimals) Format.pad(string, width) Programming and Problem Solving With Java 51 30 Num. Analysis: Bisection 20 10 f(x) Bisection program run on f(x) = x5 - 5x + 1 0 -10 -20 -30 -2 -1 0 1 x --- Find Zeros of a Function by Bisection --Enter two values that surround the value of x that makes the function 0. Value of x that gives positive value from function: -1 Value of x that gives negative value from function: -2 Bound1 Bound2 Midpoint f(Midpoint) -1.00000 -1.50000 -1.50000 -1.50000 -1.50000 -1.53125 -1.53125 -1.53906 -1.53906 -1.54102 -1.54102 -1.54150 -1.54150 -2.00000 -2.00000 -1.75000 -1.62500 -1.56250 -1.56250 -1.54687 -1.54687 -1.54297 -1.54297 -1.54199 -1.54199 -1.54175 -1.50000 -1.75000 -1.62500 -1.56250 -1.53125 -1.54687 -1.53906 -1.54297 -1.54102 -1.54199 -1.54150 -1.54175 -1.54163 0.90625 -6.66309 -2.20596 -0.50073 0.23783 -0.12241 0.05994 -0.03068 0.01477 -0.00792 0.00343 -0.00224 0.00060 Programming and Problem Solving With Java 52 2 Num. Analysis: Bisection 1.5 1 0.5 f(x) Bisection program run on f(x) = (6x3 + 4x2 + 1) / 25x 0 -0.5 -1 -1.5 -2 --- Find Zeros of a Function by Bisection --- -1 -0.5 0 0.5 x Enter two values that surround the value of x that makes the function 0. Value of x that gives positive value from function: 1.0 Value of x that gives negative value from function: -0.4 Bound1 Bound2 Midpoint f(Midpoint) 1.00000 0.30000 0.30000 0.12500 0.03750 0.03750 0.01562 0.00469 0.00469 0.00195 0.00059 0.00059 0.00024 0.00007 0.00007 0.00003 0.00001 -0.40000 -0.40000 -0.05000 -0.05000 -0.05000 -0.00625 -0.00625 -0.00625 -0.00078 -0.00078 -0.00078 -0.00010 -0.00010 -0.00010 -0.00001 -0.00001 -0.00001 0.30000 -0.05000 0.12500 0.03750 -0.00625 0.01562 0.00469 -0.00078 0.00195 0.00059 -0.00010 0.00024 0.00007 -0.00001 0.00003 0.00001 -0.00000 0.20293 -0.80740 0.34375 1.07300 -6.40099 2.56256 8.53409 -51.20012 20.48031 68.26676 -409.60002 163.84004 546.13335 -3276.80000 1310.72000 4369.06667 -26214.40000 Programming and Problem Solving With Java 53