Sunday, November 9, 2008

Iteration Statements

Iteration Statements

Java's iteration statements are for, while, and do-while. These statements create what we commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. As you will see, Java has a loop to fit any programming need.

 

While

The while loop is Java's most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

 

while(condition)

{

// body of loop

}

 

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

 

Here is a while loop that counts down from 10, printing exactly ten lines of "tick":

 

// Demonstrate the while loop.

class While {

public static void main(String args[]) {

int n = 10;

while(n > 0) {

System.out.println("tick " + n);

n--;

}

}

}

 

When you run this program, it will "tick" ten times:

tick 10

tick 9

tick 8

tick 7

tick 6

tick 5

tick 4

tick 3

tick 2

tick 1

 

Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with.

 

For example, in the following fragment, the call to println( ) is never executed:

 

int a = 10, b = 20;

while(a > b)

System.out.println("This will not be displayed");

 

The body of the while (or any other of Java's loops) can be empty. This is because a null statement (one that consists only of a semicolon) is syntactically valid in Java.

 

For example, consider the following program:

 

// The target of a loop can be empty.

class NoBody {

public static void main(String args[]) {

int i, j;

i = 100;

j = 200;

// find midpoint between i and j

while(++i < --j) ; // no body in this loop

System.out.println("Midpoint is " + i);

}

}

 

This program finds the midpoint between i and j. It generates the following output: Midpoint is 150. Here is how the while loop works. The value of i is  incremented, and the value of j is decremented. These values are then compared with one another. If the new value of i is still less than the new value of j, then the loop repeats. If i is equal to or greater than j, the loop stops.

 

Upon exit from the loop, i will hold a value that is midway between the original values of i and j. (Of course, this procedure only works when i is less than j to begin with.) As you can see, there is no need for a loop body; all of the action occurs within the conditional expression, itself.

In professionally written Java code, short loops are frequently coded without bodies when the controlling expression can handle all of the details itself.

 

do-while

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when  you would like to test the termination expression at the end of the loop rather than at the beginning.

 

Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.

 

Its general form is

 

do

{

// body of loop

} while (condition);

 

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java's loops, condition must be a Boolean expression.

 

Here is a reworked version of the "tick" program that demonstrates the do-while

loop.

 

It generates the same output as before.

 

// Demonstrate the do-while loop.

class DoWhile {

public static void main(String args[]) {

int n = 10;

do {

System.out.println("tick " + n);

n--;

} while(n > 0);

}

}

 

The loop in the preceding program, while technically correct, can be written more efficiently as follows:

 

do

{

System.out.println("tick " + n);

} while(--n > 0);

 

In this example, the expression (– –n > 0) combines the decrement of n and the test for zero into one expression. Here is how it works. First, the – –n statement executes, decrementing n and returning the new value of n. This value is then compared with zero. If it is greater than zero, the loop continues; otherwise it terminates.

 

The do-while loop is especially useful when you process a menu selection, because you will usually want the body of a menu loop to execute at least once. Consider the following program which implements a very simple help system for Java's selection and iteration statements:

 

// Using a do-while to process a menu selection

class Menu {

public static void main(String args[])

throws java.io.IOException {

char choice;

do {

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.println(" 3. while");

System.out.println(" 4. do-while");

System.out.println(" 5. for\n");

System.out.println("Choose one:");

choice = (char) System.in.read();

} while( choice < '1' || choice > '5');

System.out.println("\n");

switch(choice) {

case '1':

System.out.println("The if:\n");

System.out.println("if(condition) statement;");

System.out.println("else statement;");

break;

case '2':

System.out.println("The switch:\n");

System.out.println("switch(expression) {");

System.out.println(" case constant:");

System.out.println(" statement sequence");

System.out.println(" break;");

System.out.println(" // ...");

System.out.println("}");

break;

case '3':

System.out.println("The while:\n");

System.out.println("while(condition) statement;");

break;

case '4':

System.out.println("The do-while:\n");

System.out.println("do {");

System.out.println(" statement;");

System.out.println("} while (condition);");

break;

case '5':

System.out.println("The for:\n");

System.out.print("for(init; condition; iteration)");

System.out.println(" statement;");

break;

}

}

}

 

Here is a sample run produced by this program:

Help on:

1. if

2. switch

3. while

4. do-while

5. for

Choose one:

4

The do-while:

do {

statement;

} while (condition);

 

              In the program, the do-while loop is used to verify that the user has entered a valid choice. If not, then the user is reprompted. Since the menu must be displayed at least once, the do-while is the perfect loop to accomplish this. A few other points about this example: Notice that characters are read from the keyboard by calling System.in.read( ).

 

           This is one of Java's console input functions. Although Java's console I/O methods won't be discussed in detail until future posts, System.in.read( ) is used here to obtain the user's choice. It reads characters from standard input (returned as integers, which is why the return value was cast to char).

 

By default, standard input is line buffered, so you must press ENTER before any characters that you type will be sent to your program.

 

Java's console input is quite limited and awkward to work with. Further, most real-world Java programs and applets will be graphical and window-based. For these reasons, not much use of console input has been made in this book.

 

However, it is useful in this context. One other point: Because System.in.read( ) is being used, the program must specify the throws java.io.IOException clause. This line is necessary to handle input errors. It is part of Java's exception handling features, which are discussed in coming posts.

No comments: