Download presentation
Presentation is loading. Please wait.
1
Chapter 5 Loop Control Statements
The for Statement The while Statement The do-while Statement Numerical Accuracy Numerical Analysis Copyright 1999, James M. Slack
2
Loops: Introduction Loop Three loop statements in Java
Group of statements the computer executes over and over, as long as some criterion holds Three loop statements in Java for while do-while Programming and Problem Solving With Java
3
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
4
Loops: Kinds Two kinds of loops Counting loop 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 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
5
Event-controlled loops
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
6
The for Statement The counting loop statement in Java Example Output
for (int count = 1; count <= 5; count++) { System.out.println(count); } Output 1 2 3 4 5 Initialization Condition Increment Programming and Problem Solving With Java
7
The for Statement: Example
Sum the first 20 integers int total = 0; for (int number = 1; number <= 20; number++) { total = total + number; } System.out.println(" is " total); Output is 210 Programming and Problem Solving With Java
8
The for Statement: Example
What does this display? for (int count = 10; count <= 6; count++) { System.out.println(count); } Programming and Problem Solving With Java
9
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(" 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
10
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
11
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
12
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
13
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
14
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; public static void main[] (String args) throws TurtleException SmartTurtle myTurtle = new SmartTurtle(); myTurtle.goLeft(200); myTurtle.turnAround(); myTurtle.move(CIRCLE_SIZE); myTurtle.drawSquare(CIRCLE_SIZE * 2); myTurtle.drawCircle(CIRCLE_SIZE); } Oops! Programming and Problem Solving With Java
15
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 this.turnRight(360 / NUM_SIDES / 2); At end this.turnLeft(360 / NUM_SIDES / 2); Programming and Problem Solving With Java
16
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); } New restriction: number of sides must divide into 360 with even quotient (So can divide this by 2 for start and end angles) Ah... Programming and Problem Solving With Java
17
The while Statement while One of two event-controlled loop statements
Body keeps executing as long as condition is true Example int i = 0; while (i < 3) { System.out.println(i); i++; } Output 1 2 while Programming and Problem Solving With Java
18
The while Statement while similar to if statement while statement
while (i < 3) { System.out.println(i); i++; } if statement if (i < 3) Programming and Problem Solving With Java
19
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 Sentinel Programming and Problem Solving With Java
20
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); Trace Enter first number: 10 Enter next number: 20 Enter next number: 30 Enter next number: 0 The sum is 60 Programming and Problem Solving With Java
21
The while Statement: 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
22
The while Statement: Infinite Loop
Infinite loop example 3 answer = Keyboard.readChar("Say hi? (y/n)"); while (answer == 'y') System.out.println("Hi!"); System.out.println("Bye!"); int x = 0; while (x < 10); { System.out.println(x); x++; } Programming and Problem Solving With Java
23
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
24
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
25
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 } 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): _ Menu 0. Quit 1. Enter beginning balance 2. Enter interest rate 3. Compute ending balance Programming and Problem Solving With Java
26
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
27
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: "); case 3: System.out.println("Ending balance is " + (balance + balance * rate)); default: System.out.println("Problem with switch statement"); } // 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
28
The while Statement: Counting
Writing counting loops with while Can convert for statement to while Programming and Problem Solving With Java
29
Kinds of Loops Programming and Problem Solving With Java
30
Kinds of Loops Condition at the top Condition at the bottom
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
31
The do-while Statement
The "other" event-controlled loop statement Body keeps executing as long as condition is true Example int i = 0; do { System.out.println(i); i++; } while (i < 3); Output 1 2 Programming and Problem Solving With Java
32
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 do-while int i = 10; int i = 10; while (i < 3) do { { System.out.println(i); System.out.println(i); i++; i++; } } while (i < 3); Output (nothing) 10 Programming and Problem Solving With Java
33
The do-while Statement: Format
Poor style Preferred style do do { { do-while-body do-while-body } } while (condition); while (condition); The brace before while distinguishes it as part of a do-while Looks like the beginning of a while statement Programming and Problem Solving With Java
34
The do-while Statement: Example
Program to help children learn multiplication int guessNum = 0, response; System.out.println("What is " + operand1 + " times " + operand2 + "?"); do { guessNum++; response = Keyboard.readInt("Enter guess number " + guessNum + ": "); } while (response != operand1 * 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
35
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 ; System.out.println("Total so far: " + total); } System.out.println("Done"); Total so far: 0.1 Total so far: 0.2 Total so far: Total so far: 0.4 Total so far: 0.5 Total so far: 0.6 Total so far: 0.7 Total so far: Total so far: Total so far: Total so far: Total so far: 1.2 Total so far: 1.3 Total so far: Programming and Problem Solving With Java
36
Numerical Accuracy: Round-off
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: 1/3 = Representable in base 10: 1/4 = 0.25 Some representable numbers in base 10 are unrepresentable in binary 0.10 (decimal) = (binary) Can only store approximation of 0.10 Programming and Problem Solving With Java
37
Numerical Accuracy: Round-off
Round-off error can happen with representable numbers Example: (decimal) = (binary) Suppose computer can only store 8 binary digits Computer's version of number is an approximation Programming and Problem Solving With Java
38
Numerical Accuracy: Comparisons
Don’t compare floating-point numbers with == or != double total = 0.0; while (total != 1.0) // Avoid Instead: Use integers int total = 0; while (total != 10) // Use 1 for 1/10 Use <=, >=, <, or > while (total <= 1.0) // Good approach Check if numbers are very close // Can set exact tolerance while (Math.abs(total - 1.0) > ) ... Programming and Problem Solving With Java
39
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 = ; while (centimetersToProximaCentauri > 0.0) { // Simulate action of space probe here ... centimetersToProximaCentauri = centimetersToProximaCentauri - 1.0; } This loop is infinite: computer stores as - 1.0 One solution: use kilometers instead Programming and Problem Solving With Java
40
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) number = Keyboard.readInt("Enter next number (0 to stop): "); Must duplicate part of body before loop starts Programming and Problem Solving With Java
41
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: switch (...) case xx: break loop; ... Programming and Problem Solving With Java
42
The continue Statement
Syntax continue; or continue label; Example for (i = 0; i < 100; i++) { if (i % 2 == 0) // Ignore even numbers } 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
43
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
44
Numerical Analysis: Roots
Find roots of f(x) = x5 - 5x + 1 Plot the function Three roots: one is between -1 and -2 Programming and Problem Solving With Java
45
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 Use -1.5 as approximation of root, plug into function > 0, so it replaces old "above 0" value -1.5 Programming and Problem Solving With Java
46
Numerical Analysis: Bisection
Use bisection to find root of f(x) = x5 - 5x + 1 Next evaluate f(x) at (halfway between -1.5 and -2) f(-1.75) is < 0, so it replaces old "below 0" value -1.75 Programming and Problem Solving With Java
47
Numerical Analysis: Bisection
Keep using bisection to get as close to 0 as desired Each iteration cuts range by half Programming and Problem Solving With Java
48
Numerical Analysis: Bisection
Bisection advantages Simple and effective Little or no round-off error Bisection disadvantages Slow Only finds one root at a time Can't tell if function has other roots Appropriate for continuous intervals only Noncontinuous function Programming and Problem Solving With Java
49
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; // Width of output numbers static final int DECIMALS = 5; // 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
50
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 " double midpoint; System.out.println(Format.padRight("Bound1", WIDTH) + Format.padRight("Bound2", WIDTH) + Format.padRight("Midpoint", WIDTH) + Format.padRight("f(Midpoint)", WIDTH)); Programming and Problem Solving With Java
51
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; } Program uses Format.pad() (from Chapter 7) Format.pad(floating-point-number, width, decimals) Format.pad(string, width) Programming and Problem Solving With Java
52
Num. Analysis: Bisection
Bisection program run on f(x) = x5 - 5x + 1 --- 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 Bound Bound Midpoint f(Midpoint) Programming and Problem Solving With Java
53
Num. Analysis: Bisection
Bisection program run on f(x) = (6x3 + 4x2 + 1) / 25x --- 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.0 Value of x that gives negative value from function: -0.4 Bound Bound Midpoint f(Midpoint) Programming and Problem Solving With Java
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.