5.3 Iteration Statements

Loops allow a block of statements to be executed repeatedly (i.e., iterated). A boolean condition (called the loop condition) is commonly used to determine when to terminate the loop. The statements executed in the loop constitute the loop body. The loop body can be a single statement or a block.

Java provides three language constructs for constructing loops:

  • while statement

  • do-while statement

  • for statement

These loops differ in the order in which they execute the loop body and test the loop condition. The while and the for loops test the loop condition before executing the loop body, while the do-while loop tests the loop condition after execution of the loop body.

while Statement

The syntax of the while loop is


while (<loop condition>)
      <loop body>

The loop condition is evaluated before executing the loop body. The while statement executes the loop body as long as the loop condition is true. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. If the loop condition is false to begin with, the loop body is not executed at all. In other words, a while loop can execute zero or more times. The loop condition must be a boolean expression. The flow of control in a while statement is shown in Figure 5.3.

Figure 5.3. Activity Diagram for while Statement

graphics/05fig03.gif

The while statement is normally used when the number of iterations is not known a priori.

while (noSignOfLife())
    keepLooking();

Since the loop body can be any valid statement, inadvertently terminating each line with the empty statement (;) can give unintended results.

while (noSignOfLife());     // Empty statement as loop body!
    keepLooking();          // Statement not in the loop body.

do-while Statement

The syntax of the do-while loop is


do
     <loop body>
   while (<loop condition>);

The loop condition is evaluated after executing the loop body. The do-while statement executes the loop body until the loop condition becomes false. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. Note that the loop body is executed at least once. Figure 5.4 illustrates the flow of control in a do-while statement.

Figure 5.4. Activity Diagram for do-while Statement

graphics/05fig04.gif

The loop body in a do-while loop is invariably a statement block. It is instructive to compare the while and the do-while loops. In the examples below, the mice might never get to play if the cat is not away, as in the loop at (1). The mice do get to play at least once (at the peril of losing their life) in the loop at (2).

while (cat.isAway()) {       // (1)
    mice.play();
}

do {                         // (2)
    mice.play();
} while (cat.isAway());

for Statement

The for loop is the most general of all the loops. It is mostly used for counter-controlled loops, that is, when the number of iterations is known beforehand.

The syntax of the loop is as follows:


for (<initialization>; <loop condition>; <increment expression>)
      <loop body>

The <initialization> usually declares and initializes a loop variable that controls the execution of the <loop body>. The <loop condition> is a boolean expression, usually involving the loop variable, such that if the loop condition is true, the loop body is executed; otherwise, execution continues with the statement following the for loop. After each iteration (i.e., execution of the loop body), the <increment expression> is executed. This usually modifies the value of the loop variable to ensure eventual loop termination. The loop condition is then tested to determine if the loop body should be executed again. Note that the <initialization> is only executed once on entry to the loop. The semantics of the for loop are illustrated in Figure 5.5, and can be summarized by the following equivalent while loop code template:


<initialization>
while (<loop condition>) {
    <loop body>
    <increment expression>
}

Figure 5.5. Activity Diagram for the for Statement

graphics/05fig05.gif

The following code creates an int array and sums the elements in the array.

int sum = 0;
int[] array = {12, 23, 5, 7, 19};
for (int index = 0; index < array.length; index++)   // (1)
    sum += array[index];

The loop variable index is declared and initialized in the <initialization> section of the loop. It is incremented in the <increment expression> section. The for loop defines a local block such that the scope of this declaration is the for block, which comprises the <initialization>, the <loop condition>, the <loop body> and the <increment expression> sections.

The loop at (1) showed how a declaration statement can be specified in the <initialization> section. Such a declaration statement can also specify a comma-separated list of variables.

for (int i = 0, j = 1, k = 2; ... ; ...) ...;      // (2)

The variables i, j, and k in the declaration statement all have type int. All variables declared in the <initialization> section are local variables in the for block and obey the scope rules for local blocks. However, note that the following code will not compile, as variable declarations of different types (in this case, int and String) require declaration statements that are terminated by semicolons.

for (int i = 0, String str = "@"; ... ; ...) ...;  // (3) Compile time error.

The <initialization> section can also be a comma-separated list of expression statements (see Section 4.3, p. 113). For example, the loop at (2) can be rewritten by factoring out the variable declaration.

int i, j, k;  // Variable declaration
for (i = 0, j = 1, k = 2; ... ; ...) ...;      // (4) Just initialization

The <initialization> section is now a comma-separated list of three expressions. The expressions in such a list are always evaluated from left to right. Note that the variables i, j, and k are now obviously not local to the loop.

Declaration statements cannot be mixed with expression statements in the <initialization> section, as is the case at (5) in the following example. Factoring out the variable declaration, as at (6), leaves a legal comma-separated list of expression statements only.

// (5) Not legal and ugly.
for (int i = 0, System.out.println("This won't do!"); flag; i++) {
    // loop body
}

// (6) Legal, but still ugly.
int i;
for (i = 0, System.out.println("This is legal!"); flag; i++) {
    // loop body
}

The <increment expression> can also be a comma-separated list of expression statements. The following code specifies a for loop that has a comma-separated list of three variables in the <initialization> section, and a comma-separated list of two expressions in the <increment expression> section.

// Legal usage but not recommended.
int[][] sqMatrix = { {3, 4, 6}, {5, 7, 4}, {5, 8, 9} };
for (int i = 0, j = sqMatrix[0].length - 1, asymDiagonal = 0;  // initialization
     i < sqMatrix.length;                                      // loop condition
     i++, j--)                                          // increment expression
     asymDiagonal += sqMatrix[i][j];                    // loop body

All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The "crab", (;;), is commonly used to construct an infinite loop, where termination is presumably achieved through code in the loop body (see next section on transfer statements):

for (;;) Java.programming();       // Infinite loop