Loop Constructs

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 4.  Flow Control


It is quite common in computer programming to want to perform a task a specific number of times or until some condition is satisfied. Java provides three loop constructs that facilitate this: the while statement, do-while statement, and for statement.

The while Statement

The while statement tells the compiler to repeatedly execute a set of code until a condition is satisfied. The general form of the while statement is

 while( boolean_condition ) {     //statements;  } 

The statements contained within the braces will be executed as long as the boolean condition is true. When the boolean becomes false, the while loop ceases executing these statements and continues execution at the statement immediately following the while statement block. Consider displaying the numbers between 1 and 10, see Listing 4.1.

Listing 4.1 WhileExample.java
 1: public class WhileExample {  2:    public static void main( String[] args ) {  3:       int i=1;  4:       while( i <= 10 ) {  5:          System.out.println( "i=" + i );  6:          i++;  7:       }  8:    }  9: } 

Listing 4.1 defines a new class named WhileExample. Line 3 creates an int and initializes it to 1. Line 4 defines a while loop that repeats the statements in lines 5 and 6, while i is less than or equal to 10. Line 3 initializes i to 1, and line 6 increments i.

If you were to forget to increment i, what would happen? The boolean value that the while statement is evaluating would never become false (i would remain at 1 indefinitely), and hence line 5 would be executed indefinitely. This is referred to as an infinite loop and is a programming error. Be sure that the condition in your loops will eventually change and cause the while statement to cease!

There is one alternative to breaking out of the while loop before the condition becomes false: the break statement. Not only does the break statement enable you to skip over cases in a switch statement, its full purpose is to stop execution and continue at the first statement following the block of code (delimited by braces) that contains it. Thus, break enables you to continue execution after the while loop.

The do Statement

Are the statements in a while loop guaranteed to be executed at least once? Consider the following example:

 int i = 10;  while( i < 10 ) {     System.out.println( "i is less than 10" );  } 

The while loop evaluates the boolean condition and if it is true it executes the statements in its body; then it reevaluates the condition this process continues until the condition is false. Because you sometimes would like to be assured that the code in your loop will execute at least once, Java has defined a do while statement. It has the general form:

 do {     // statements;  } while( boolean_condition ); 

The do while statement executes the statements in its body, and then evaluates the boolean condition, as opposed to the while statement evaluating the boolean condition prior to executing the statements in its body. The do while statement ensures that the statements in the body are executed at least once.

Listing 4.2 shows an example using the do while statement.

Listing 4.2 DoWhileExample.java
 1: public class DoWhileExample {  2:    public static void main( String[] args ) {  3:       int a = 0;  4:       do {  5:         System.out.println( "a=" + a );  6:          a += 2;  7:       } while( a <= 10 );  8:    }  9: } 

Listing 4.2 is very similar in functionality to Listing 4.1 (the while loop). Line 3 creates a new int named a and initializes it to 0. The do loop prints the value of a in line 5, increases its value by 2 in line 6, and then evaluates its value in line 7. The output for the DoWhileExample class is

 0  2  4  6  8  10 

If a was 20, lines 5 and 6 would be executed before the while in line 7 could stop its execution. The output would be

 10 

do while and while statements are very similar with the sole difference that do while ensures the body of the loop will be executed at least once, and the while loop might never execute its body. In practice programmers tend to use while loops over do while, but the choice will be made based on the problem you are trying to solve.

The for Statement

To this point the while and do while statements have been used to iterate over a variable (i and a) and perform some function on the interim value. while and do while statements are not only used for counting, but for any function that can resolve to a boolean value. If you have the need to iterate a specific number of times Java provides the for statement. The for statement is typically used for counting or repeating code executions a specific number of times. There are other uses as you will see, but counting is the typical case. The general form of the for statement is

 for( initialization_statement; boolean_condition; iteration_statement ) {     // statements;  } 

The initialization statement is executed before the loop starts and is used to initialize the variable or variables that will be used in the loop. Next the boolean condition is evaluated if it is true, the body of the for loop will be executed. Finally, the iteration statement will be executed, and the boolean condition will be evaluated again, ad infinitum. Looking at the while loop, this is really what the examples did:

 1: public class WhileExample {  2:    public static void main( String[] args ) {  3:       int i=1; // Initialization statement  4:       while( i <= 10 ) {  //  Boolean comparison  5:          System.out.println( "i=" + i ); // Body  6:          i++; // Iteration statement  7:       }  8:    }  9: } 

Listing 4.3 shows how this example can be rewritten using a for statement.

Listing 4.3 ForExample.java
 public class ForExample {     public static void main( String[] args ) {        for( int i=1; i<= 10; i++ ) {           System.out.println( "i=" + i );        }     }  } 

The result of Listing 4.3, as you would expect, is

 1  2  3  4  5  6  7  8  9  10 

Before leaving the for loop there are some specific rules that you need to know:

  • The examples in this section have declared and defined a new variable in the initialization section of the for statement; this is permissible and encouraged, but not required. The requirement is only the initialization of the variable, not necessarily its creation. Thus, the following is legal:

     int i = 0;  for( int i=0; i<10; i++ ) {     // statements;  } 

  • Furthermore because you are managing the variables and Boolean condition in the for statement, you do not have to do anything in the initialization section. Thus, the following is also legal:

     int i = 0;  for( ; i<10; i++ ) {     // statements;  } 

Scope

Programmers found that they often needed a variable for the sole purpose of iterating through a loop; this variable is commonly referred to as the loop control variable. Because of this, most programming languages, including Java, offered programmers the ability to declare and initialize one or more variables in the initialization section of the for loop. There is however, a set of scoping rules that define where that variable is visible. Any variable declared in the initialization section of a for loop is only visible inside that for loop's code block.

The region of code where a variable is visible and accessible is referred to as that variable's scope. In the for loop, the braces that follow the for statement define a block of code; in this case this is the body of the for loop. The scope of all variables defined in the initialization section of a for loop is the body of the for loop. What does this mean practically? Consider the following examples:

 1: int i = 1;  2: System.out.println( "a=" + a ); // error; a is not visible (out of scope)  3: for( int a=0; a<10; a++ ) {  4:    System.out.println( "a=" + a ); // a is visible (in scope)  5:    System.out.println( "i=" + i ); // i is visible (in scope)  6: }  7: System.out.println( "a=" + a ); // error; a is not visible (out of scope)  8: System.out.println( "i=" + i ); // i is visible (in scope) 

The for loop encompasses lines 3 6, and a is the loop control variable. a is therefore visible in the for statement and between the braces that define the body of the for loop (lines 3 6). Any attempt to access a outside of the body of the for loop will result in a compilation error, which is shown in lines 2 and 7.

The variable i, on the other hand, is defined outside the body and initialization section of the for loop and therefore is visible outside the for loop (line 8) as well as inside the for loop (line 5). You will learn more about the scoping rule later in the book, but a standard rule of thumb is that a variable is visible in its code block after its declaration and in child code blocks, but it is not visible outside its code block. Consider the following:

 // Visible: none, Not Visible: a, b, c, d  int a = 10;  // Visible: a, Not Visible: b, c, d  for( int b=0; b<10; b++ ) {     // Visible: a, b, Not Visible: c, d     while( b<5 ) {        int c = a*b;        // Visible: a, b, c, Not Visible: d     }     while( b>5 {        int d = b-a;        // Visible: a, b, d, Not Visible: c     }     // Visible: a, b Not Visible: c, d  }  // Visible: a, Not Visible: b, c, d 

This set of rules is referred to as block scoping rules because it defines the visibility, or scope, of variable based on the code block to which it belongs.

Multiple Variables

You are not restricted to defining a single variable in the initialization section of the for loop, you can define multiple variables. The only restriction is that they must all be of the same type. You might also update multiple variables in the iteration statement. The key is to separate the operations by commas, see Listing 4.4.

Listing 4.4 ForMultipleExample.java
 1: public class ForMultipleExample {  2:    public static void main( String[] args ) {  3:       for( int i=1, j=10; i<=10; i++, j-- ) {  4:          System.out.println( "i=" + i );  5:          System.out.println( "j=" + j );  6:          System.out.println( "i*j=" + i*j );  7:       }  8:    }  9: } 

Listing 4.4 shows the creation of two integers, i and j, in the initialization section of the for loop in line 3. Note that a comma separates the initialization of the two variables. The iteration statement in the for loop modifies both variables: it increments i and decrements j. Both i and j are visible inside the body of the for loop as well as in all parts of the for loop statement (initialization, comparison, and iteration statements).

Breaking Out of Loops

As you learned earlier in this chapter, there are some occasions when you want to exit a loop early; this is facilitated by the break statement. The break statement is not only applicable to the while loop, but to all of our loops, including the for loop.

The break statement causes the execution of the program to break from the point of the break statement and continue at the statement immediately following the code block that contains it. Listing 4.5 demonstrates how the break statement is used.

Listing 4.5 BreakExample.java
 1:  public class BreakExample {  2:     public static void main( String[] args ) {  3:        for( int i=1; i<= 10; i++ ) {  4:           if( i == 5 ) {  5:              break;  6:           }  7:           System.out.println( "i=" + i );  8:        }  9:        System.out.println( "Done" );  10:    }  11: } 

The output from Listing 4.5 is

 i=1  i=2  i=3  i=4  Done 

The for loop defined by lines 3 8 counts from 1 to 10 and prints the value out to the screen. Line 4 defines an if statement that checks whether i is equal to 5, and if it is it subsequently issues the break statement in line 5. At this point the program execution skips over line 7 (it does not print i=5) and continues with the statement immediately following the for loop line 9 and prints Done. The output demonstrates this.

Continuing Execution in a Loop

How would you implement a for loop that printed all of the values between 1 and 10 except for 5 and 7? Using the break statement you could print the values from 1 to 4, and then break out of the loop, but the requirement is after you skip 5 that you skip over this iteration of the loop and continue with the next iteration.

Java provides this functionality through the continue statement. It causes the execution of the current iteration of the loop to cease, and then continue at the next iteration of the loop. Listing 4.6 shows how to solve this problem using the continue statement.

Listing 4.6 ContinueExample.java
 1:  public class ContinueExample {  2:     public static void main( String[] args ) {  3:        for( int i=1; i<= 10; i++ ) {  4:           if( i == 5 || i == 7 ) {  5:               continue;  6:            }  7:           System.out.println( "i=" + i );  8:        }  9:        System.out.println( "Done" );  10:    }  11: } 

The output of Listing 4.6 is

 i=1  i=2  i=3  i=4  i=6  i=8  i=9  i=10  Done 

The for loop, defined by lines 3 8 of Listing 4.6, counts from 1 to 10 and prints the value (line 7). Line 4 however, checks the value of i to see if it is 5 or 7; if it is, it issues the continue statement in line 5. The continue statement tells the compiler to skip over the rest of this iteration of the for loop (line 7) and continue with the next iteration (execute the iteration statement in the for loop, and then the comparison). From the output you can see that when line 4 encountered the values 5 and 7 it skipped over line 7 and did not print the value of i, but continued with the next iteration of the for loop.

Labels

The break and continue statements are great for breaking out of, or continuing out of, a single loop, but they do not provide support for multiple nested loops. Consider building a mathematical Times Table from 1 to 10, a possible solution is to use nested for loops. A nested loop is a loop that is contained within the body of another loop. Listing 4.7 shows code that generates a Times Table.

Listing 4.7 TimesTableExample.java
 1:  public class TimesTableExample {  2:     public static void main( String[] args ) {  3:        for( int i=1; i<=10; i++ ) {  4:           for( int j=1; j<=10; j++ ) {  5:              System.out.print( (i*j) + "\t" );  6:           }  7:           System.out.println();  8:        }  9:     }  10: } 

The output from Listing 4.7 is

 1       2       3       4       5       6       7       8       9       10  2       4       6       8       10      12      14      16      18      20  3       6       9       12      15      18      21      24      27      30  4       8       12      16      20      24      28      32      36      40  5       10      15      20      25      30      35      40      45      50  6       12      18      24      30      36      42      48      54      60  7       14      21      28      35      42      49      56      63      70  8       16      24      32      40      48      56      64      72      80  9       18      27      36      45      54      63      72      81      90  10      20      30      40      50      60      70      80      90      100 

Thus, if you look at any value in the top row and multiply it by the value found in left column, you find the answer where the row and column intersect. Consider 4 times 6: The first row number, 4, multiplied by the sixth row number, 6, results in 24, which is where they intersect (row 6, column 4).

The generation of this Times Table is accomplished in Listing 4.7 by defining a for statement for lines 3 to 8 that counts from 1 to 10, and then defining a nested for loop from lines 4 to 6 that also counts from 1 to 10. Line 5 multiplies the value from the outer loop by the value of the nested, or inner, loop, and thus the Times Table is generated. To this point you have been using the System.out.println() call to print a value to the screen, but in this case line 5 uses System.out.print instead. The difference is that println() prints a carriage return and linefeed after printing the value, whereas print() prints the value and leaves the output at the end of the print without adding a carriage return or line feed.

Now consider building this Times Table, but when you reach a product of 25, stop completely. Java enables you to define a point in your code that break and continue statements can be anchored to, called a label, so their functionality will be tied to that specific location in code. With a label defined, you can tell the break or continue statements to break or continue to that label by passing them the label's name.

A label is defined by a string of text (same rules apply to defining a label name as to defining a variable name) followed by a colon. The following loop defines the location that break and continue statements can be sent to. The break and continue statements can either break out of or continue to the current loop (as you have seen), or specify a specific label to break out of. This is accomplished by passing the break or continue statement the label. The general form for this operation is

 mylabel:     for( int a=0; a<10; a++ ) {        for( int b=0; b<10; b++ ) {           break mylabel;        }     } 

Listing 4.8 shows the solution to the partial Times Table example.

Listing 4.8 TimesTableExample2.java
 1:  public class TimesTableExample2 {  2:     public static void main( String[] args ) {  3:        outer:  4:        for( int i=1; i<=10; i++ ) {  5:           for( int j=1; j<=10; j++ ) {  6:              if( ( i*j ) == 25 ) {  7:                 break outer;  8:              }  9:              System.out.print( (i*j) + "\t" );  10:          }  11:          System.out.println();  12:       }  13:       System.out.println( "Done" );  14:    }  15: } 

The output from Listing 4.8 is

 1       2       3       4       5       6       7       8       9       10  2       4       6       8       10      12      14      16      18      20  3       6       9       12      15      18      21      24      27      30  4       8       12      16      20      24      28      32      36      40  5       10      15      20      Done 

Line 3 defines the label outer, and then line 7 issues a break statement passing it the label name outer. When line 6 finds two numbers where the product is 25 it breaks out of both loops and continues at the statement immediately following the loop associated with the label.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net