The do-while Statement – Control Flow

4.6 The do-while Statement

The syntax of the do-while loop is

do
loop_body

while (
loop_condition
);

In a do-while statement, the loop condition is evaluated after executing the loop body. The loop condition must evaluate to a boolean or Boolean value. The value of the loop condition is subjected to unboxing if it is of the type Boolean. 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 any statement immediately following the loop. Note that the loop body is executed at least once. Figure 4.7 illustrates the flow of control in a do-while statement.

Figure 4.7 Activity Diagram for the do-while Statement

The loop body in a do-while loop is invariably a statement block. It is instructive to compare the while and do-while loops. In the examples that follow, 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).

Click here to view code image

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

4.7 The for(;;) Statement

The for(;;) loop is the most general of all the loops. It is mostly used for counter-controlled loops, in which the number of iterations is known beforehand.

The syntax of the loop is as follows:

Click here to view code image

for (
initialization
;
loop_condition
;
update_expression
)
loop_body

The initialization usually declares and initializes a loop variable that controls the execution of the loop body. The loop body can be a single statement or a statement block. The loop condition must evaluate to a boolean or Boolean value. In the latter case, the reference value is converted to a boolean value by unboxing. The loop condition usually involves the loop variable, and if the loop condition is true, the loop body is executed; otherwise, execution continues with any statement following the for(;;) loop. After each iteration (i.e., execution of the loop body), the update 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 whether the loop body should be executed again. Note that the initialization is executed only once, on entry into the loop. The semantics of the for(;;) loop are illustrated in Figure 4.8, and are summarized by the following equivalent while loop code template:

Click here to view code image

initialization
while (
loop_condition
) {
loop_body
update_expression
}

Figure 4.8 Activity Diagram for the for Statement

The following code creates an int array and sums the values in the array:

Click here to view code image

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 update expression section. This loop is an example of a forward for(;;) loop, where the loop variable is incremented.

The next code snippet is an example of a backward for(;;) loop, where the loop variable is decremented to sum the values in the array:

Click here to view code image

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

It is instructive to compare the specification of the loop header in the forward and backward for(;;) loops in these examples.

The loop at (1) earlier 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:

Click here to view code image

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(;;) statement and obey the scope rules for local blocks, as do any variables declared in the loop body. The following code will not compile, however, as variable declarations of different types (in this case, int and String) require declaration statements that are terminated by semicolons:

Click here to view code image

for (int i = 0, String str = “@”; … ; …) …;  // (3) Compile-time error

The initialization section can also be a comma-separated list of expression statements (§3.3, p. 101). Any value returned by an expression statement is discarded. For example, the loop at (2) can be rewritten by factoring out the variable declarations:

Click here to view code image

int i, j, k;                                       // Variable declaration
for (i = 0, j = 1, k = 2; … ; …) …;          // (4) Only 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, and their values are discarded. Note that the variables i, j, and k at (4) are 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.

Click here to view code image

// (5) Not legal and ugly:
for (int i = 0, System.out.println(“This won’t do!”); flag; i++) { // Error!
  // loop body
}
// (6) Legal, but still ugly:
int i;                                       // Declaration factored out.
for (i = 0, System.out.println(“This is legal!”); flag; i++) {     // OK.
  // loop body
}

The update 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 update expression section:

Click here to view code image

// Legal usage but not recommended, as it can affect code comprehension.
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–)                                          // update expression
  asymDiagonal += sqMatrix[i][j];                       // loop body

All sections in the for(;;) header are optional. Any or all 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”, (;;), can be used to construct an infinite loop, where termination is presumably achieved through code in the loop body (see the next section on transfer statements):

Click here to view code image for (;;) doProgramming();       // Infinite loop