LOOPS while loops dowhile loops for loops break
LOOPS • while loops • do-while loops • for loops • break statement • continue statement • Common loop errors 2/1/2022 1
Looping • Causes computer to execute section of code repeatedly – uses booleans (true and false) as loop conditions • when boolean is false, the loop condition equals the exit condition and the loop is terminated – as with conditionals, section of code can be single line or many lines enclosed in curly braces – section of code executed is typically called the loop’s body 2/1/2022 2
Looping • Three loop structures in Java – while loop – do-while loop – for loop • Differ only in relation between body and loop condition – some loops execute body and then test – others test before executing body 2/1/2022 3
The while loop • while loops continue while loop condition is true – tests loop condition before executing body – if loop condition is false first time through, the body is not executed at all while (<loop condition>) { <loop body> } 2/1/2022 4
The while loop • Loop condition can be any boolean expression • Examples of loop conditions: – num. Classes < 30 – people. Standing <= max. People – check. Amount() <= acct. Balance – is. Square() • predicate methods (return boolean) 2/1/2022 5
The while loop • Multiple conditions can be combined using logical operators (and, or, not) – (num. Classes >= 3) && (num. Classes <=5) – (people. Standing <= max. People) || (max. People < 50) 2/1/2022 6
A while Flowchart <previous statement> Is <loop condition> TRUE? Yes <loop body> No <rest of program> 2/1/2022 7
Example Code • See Loop. Frame. java – Has example of all three loops • while loop • do-while loop • for loop – Has graphical output on screen • See class Daruma in file Daruma. java – And textual output in the console window • Check out the value of variable i (the loop counter) 2/1/2022 8
The do-while Loop • do-while always executes loop body at least once by switching order of test and body • <loop condition> is boolean expression. 2/1/2022 9
The do-while Loop <previous statement> <loop body> Is <loop condition> TRUE? Yes No <rest of program> 2/1/2022 10
do-while vs. while • In both loops – stops executing body if loop condition is false – you must make sure loop condition becomes false by some computations lest you “infinite loop” – infinite loop means your loop’s loop condition is such that it will never turn false, i. e. , the exit condition never occurs • do-while – body always executed at least once 2/1/2022 – loop condition tested at bottom of loop 11
do-while vs. while • while – may not execute at all – loop condition tested before body – loop condition variables must be set before loop entry – useful for screening bad data that might cause statements within loop to fail • e. g. , while (ref != null) 2/1/2022 12
for Loops • Most specialized loop construct for(<init-expr>; <loop condition>; <update>) { <loop body> } – <init-expr>: expression for setting initial value of loop counter • Traditionally use single character identifier • For example, i (for “index”) – <loop condition>: (true or false) test involving loop counter to determine if loop should execute – <update>: expression that modifies loop 2/1/2022 counter 13
for Loops – <init-expr> is executed at start of loop code, – <loop condition> is checked at the start of every loop (including the first) – <update> is run at the end of every <loop body>, just before returning to the top of the loop • Typically used to execute loop body predetermined number of times – while and do-while loops can execute body for undetermined number of times 2/1/2022 • based on boolean 14
for Flowchart <init-counter> <update counter> Is <loop condition> TRUE? Yes <loop body> No <rest of program> 2/1/2022 15
for == while – for(expr 1; expr 2; expr 3) statement; • Is equivalent to: – expr 1; while(expr 2){ statement; expr 3; } 2/1/2022 16
Comma in for Loops • Can put commas in for loops • Evaluated left to right int a=0, b=0; for(a=0, b=10; a<b; a++, b--) System. out. println("a="+a+ ", b="+b); • What’s the output? – See Loop. Consule. Output. java 2/1/2022 17
Nested Loops • Can have loops within loops (or any other combination of nested repetition & selection statements) – for(int a=0; a<5; a+=2){ for(b=3; b>0; b--){ System. out. print("b="+b); } //inner loop System. out. println("a="+a); } //outer loop • What’s the output? – See Loop. Consule. Output. java 2/1/2022 18
Repetition – 3 Choices 1. for(initialize, condition, increment) • for(int i=0; i<5; i=i+1) { System. out. println("five"); } 2. do{statements} while(condition) • do{ System. out. println("one"); }while(1 < 0); 3. while (condition) {statements; } • while(5==5){ System. out. println("infinity"); } 2/1/2022 • What’s the output? (See Loop. Consule. Output. java) 19
Example Code • See Decrementing. Nested. Loop. Frame. java – Has nested for loops • Displays Darumas from the right to the left, one column at a time – Outer loop decrements by 100 & inner loop increments by 100 – Also see text output in console window 2/1/2022 20
Guidelines for Choosing • for loop is called definite loop because you can typically predict how many times it will loop – for loop is typically used for math-related loops like counting finite sums • while and do-while loops are indefinite loops, as you do not know a priori when they will end. 2/1/2022 21
Guidelines for Choosing • while loop is good for situations where boolean condition could turn false at any time • do-while loop is used in same type of situation as while loop, but when code should execute at least once 2/1/2022 22
Alter Flow of Control Within Loop • break; – Immediately exit from while, for, dowhile, or switch statements • continue; – Skips the remaining statements – Performs the next iteration of while, for, or do-while loop 2/1/2022 23
break //we’d like to eat 10 cookies for (int i = 0; i < 10; i++) { if(cookie. Jar. number. Of. Cookies() == 0 ){ break; // if there are no cookies left, // we should break out of loop // because we can’t eat any more! } eat. ACookie(); //some are left } // execution continues here // after loop is done // or after break statement 2/1/2022 24
Example Code • See Break. Frame. java – Has example of break statement • Breaks out of the inner loop when x-coordinate is a certain value • So this stops the inner loop (which loops through ycoordinate) • The specified column will not be drawn – Check out textual output in the console window • As you can see, the inner loop stops (y-coordinate) 2/1/2022 25
continue • When executed in while, for, dowhile structure, continue skips remaining statements in body of that structure, and proceeds with next iteration of loop – useful if there is list of data that you are looping over and you want to skip processing of data that is somehow “illegal” 2/1/2022 26
continue // try on all shirts that hang on a rack for (int i = 0; i < 20; i++) { if( !rack. is. Shirt. On. Hanger(i) ) { // if there’s no shirt on the current // hanger, skip to the next iteration continue; } // only do this if shirt is on hanger // get the shirt & try the shirt on Shirt shirt = rack. get. Shirt. On. Hanger(i); try. On. Shirt( shirt ); } 2/1/2022 27
continue • In while and do-while structure, execution continues by evaluating loopcontinuation condition • In for structure, execution continues by incrementing counter and then evaluating loop condition 2/1/2022 28
Example Code • See Continue. Frame. java – Has example of continue statement • Skips the remaining code, so Daruma is not drawn • Then continues to next value of the inner loop when ycoordinate is a certain value • So the specified row in each column will not be drawn – Check out textual output in the console window • As you can see, the inner loop does not stop (ycoordinate) 2/1/2022 29
Class Exercise • Was the output of the following code? – See Tracing. java • Similar code will be on the next exam • In order to help you trace through the code, the boxes have different colors • On the actual exam, all the boxes will be black 2/1/2022 30
Boolean Flags • A boolean flag is a boolean variable that denotes a condition (e. g. , done, working, available) – set in one place, tested in another • Boolean flags can also be used as the loop condition 2/1/2022 31
Boolean Flags • Implementing a for loop, using while: boolean done = false; int i = 0; while (!done) { i++; if (i == 5) done = true; } – Notice that boolean flag is set within loop 2/1/2022 32
Example Code • See Loop. Frame 2. java – Has code for • • Boolean flags Empty intervals Off by one errors Other loop errors – Has both graphical and textual output 2/1/2022 33
Empty Intervals • What happens if we try to add integers in this loop? public int sum() { int temp_sum = 0; for (int i = 1; i < 1; i++) temp_sum += i; return temp_sum; } • Answer: Body of loop is not executed – boolean is false for initial value of counter 2/1/2022 34
Empty Intervals • Correct example: /* This method sums all numbers from 1 up to and including the number specified */ public int sum(int number) { int temp_sum = 0; for (int i = 1; i <= number; i++) temp_sum += i; return temp_sum; } 2/1/2022 35
Off-by-one Errors • Occur when loop executes one too many or one too few times • Example: Add even integers from 2 to number, inclusive. . . int count = 2; int result = 0; while (count < number) { result += count; count += 2; } 2/1/2022 36
Off-by-one Errors • Produces incorrect result if number is assigned an even value. Values from 2 to number-2 will be added (i. e. , number excluded) • Should be: while (count <= number) {. . . } • Now, value of number is included in summation 2/1/2022 37
Syntax: Other Loop Errors • Make sure test variables have proper values before loop is entered product = 0; do { product *= 2; } while (product < 100); /* what will happen here? */ 2/1/2022 38
Syntax: Other Loop Errors • Make sure tests check proper conditions for (int i = 1; i != 100; i += 2) { // do something here } /* will we ever get here? */ 2/1/2022 39
Syntax: Other Loop Errors • ALWAYS HAND SIMULATE first, last, and typical case through a loop to avoid offby-one or infinite loop errors – the first and last cases of a loop’s execution are called boundary or edge conditions – hand simulation doesn’t just apply to loops, use it for everything! – Trust us – it saves debugging time!!! 2/1/2022 40
Loops & Variable Scope • What is a variable’s scope? – Where the variable is visible in the program • Where does a variable’s scope begin & end? – It begins where the variable is declared, and ends at the next right bracket ('}') • What is a variable’s scope if it is declared within a loop, or within a for statement? – Only within the loop body • Note that variables declared outside a loop are visible within a loop 2/1/2022 41
Example Code • See Example 3. java – Variables declared within the loop are red int x = 10; //declared outside loop for(int i = x; i > 0; i -= 4){ int y=10; //declared inside loop x--; y++; System. out. println("i = "+ i); System. out. println("x = "+ x); System. out. println("y = "+ y); } //y & i are out of scope after "}" System. out. println("i = "+ i); //bug! System. out. println("x = "+ x); 2/1/2022 System. out. println("y = "+ y); //bug!42
- Slides: 42