Unformatted text preview:

v Assume you have a Mouse object named “mouse” that is able to climb steps using the message: mouse.step (); // Note: NO argument v Write a code fragment to get the mouse to climb 5 stepsLoops v Loops are used to make code more succinct by eliminating repeated lines of code. v Write a code fragment that displays the numbers between 1 and 11 inclusive. Assume an OutputBox object named outBox has been declared, created, and sent the message outBox.show(); v These are examples of “count-controlled” loops. They must have steps to initialize, test, and increment (i.e., increase or decrease the counter).v Write a code fragment to have a Mouse object named “mouse” climb to the next landing in a set of stairs. Assume the Mouse class has an instance method named atLanding() that returns a boolean value of true or false. v How would your code change if you wanted the mouse to climb to the next Nth landing?The while Statement v Allows a program to execute a statement repeatedly while a condition is true v Syntax: while (<condition>) { <loop body> } while : a Java reserved word <condition>: some boolean expression <loop body>: 0, 1, or more Java statements v Using curly braces {} is optional if only one statement is contained within the loop body. However, one should ALWAYS use curly braces regardless of the number of statements contained within the body (i.e., use “Defensive Programming”). v Control-Flow Diagram: v As long as the <condition> evaluates to true, the <loop body> will continue to be executed. false true CONDITION (boolean expression) Loop Body (0, 1, or more Statements)The do...while Statement v Allows a loop’s condition to be tested AFTER it’s loop body is executed v Suitable when you want the loop body to execute at least once v Syntax: do { <loop body> } while (<condition>); do: a Java reserved word <condition>: some boolean expression <loop body>: 0, 1, or more Java statements v Using curly braces {} is optional if only one statement is contained within the loop body. However, one should ALWAYS use curly braces regardless of the number of statements contained within the body (i.e., use “Defensive Programming”). v Control-Flow Diagram: v The <loop body> will be executed at least once. Then, as long as the <condition> evaluates to true, the <loop body> will continue to be executed. v A semi-colon ALWAYS terminates a do...while statement false true CONDITION (boolean expression) Loop Body (0, 1, or more Statements)The for Statement v Syntax: for (<initialization>; <condition>; <increment>) { <loop body> } for: a Java reserved word <loop body>: 0, 1, or more Java statements <initialization> (optional): • an assignment statement (with or without declaration) • the variable assigned a value is called the “control variable” • example: int i = 0 count = 0 (count must be already declared) <condition> (optional): some boolean expression <increment> (optional): • some arithmetic expression that increases or decreases a variable • example i++ j-- i += 2 v Control-Flow Diagram: false true CONDITION (boolean expression) Loop Body (0, 1, or more Statements) Increment Initialization (Assignment Statement)The for Statement...continued v Using curly braces {} is optional if only one statement is contained within the loop body. However, one should ALWAYS use curly braces regardless of the number of statements contained within the body (i.e., use “Defensive Programming”). v As long as the <condition> evaluates to true, the <loop body> will continue to be executed. v Examples: for (int i = 0; i < array.length; i++) { /*Do Something to each cell of array */ } FoodCenterCollection fcc = tank.getFoodCenters (); for (FoodCenter fc = fcc.nextFoodCenter(); fcc.hasMoreFoodCenters(); fc = fcc.nextFoodCenter()) { if (fc.getPosition().equals (fish1.getPostion()) { fish1.eat(); } } v Syntactically legal for loops: for ( ; ; ) {/* Do Something */} // An infinite loop for (int i = 0; ; ) { break;} // Nothing more than // an assignment int c = 0; for ( ; c <= 10; c++) { outBox.printLine (c); }The for Statement...continued v Nested for loops: for loops can be nested within one another for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 3; j++) { outBox.print (“#”); } outBox.skipLine (); }Rewrite the following for loop as a while loop: int start = inBox.getInteger (“Start”); int stop = inBox.getInteger (“Stop”); int total = 0; for (int count = start; count <= stop; count++) { total += count; } outBox.printLine (“The total is: “ + total);Loops...continued v Infinite Loops: When the condition never evaluates to false int product = 0; while (product < 100) { product *= 10; } int count = 1; while (count != 10) { count += 2; } // while loop eventually terminates due // to an overflow error double count = 0.0; while (count < 1.0) { count += 0.3333333; } v Off-By-One Errors: When the loop repeats exactly one time more or less than the number of times it should repeat int count = 1; while (count < 10) { count++; } To have the loop repeat N times: counter = 0; while (counter < N) {} counter = 1; while (counter <= N) {} ORv Pre-Test vs. Post-Test Loops Pre-Test (e.g., while, for): Test condition THEN execute loop body Post-Test (e.g., do…while): Execute loop body THEN test condition v Priming Setting a variable to some value prior to the loop in order to ensure that the loop will be executed. int n = 1, total = 0; while (n != 0) { n = inBox.getInteger (); total += n; } v Count-Controlled Loops Use of a counter in order to repeat a loop a precise number of times. int count = 0, total = 0; while (count <= 5) { total += count; count++; } v Sentinel Controlled Loops Use a variable in order to repeat a loop until that variable reaches some set of “sentinel” values. /* See Priming for example */v Flag Controlled Loops Use a boolean variable (i.e., “flag”) in order to repeat a loop until the variable becomes false. The flag is set to true or false based on one or more conditions. The following code sums the first 11 positive odd numbers entered by a user. The loop can end early if a number less than zero is entered.


View Full Document

UW-Madison COMPSCI 302 - Chapter 7 Notes - Loops

Download Chapter 7 Notes - Loops
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 Notes - Loops 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 Notes - Loops 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?