Saturday 9 May 2015

Controlling Your Program in Java - Iterative Statement

Iteration

Iteration is an important concept in any computer language. Without the ability to loop or iterate through a set of values, our ability to solve real-world problems would be severely limited. Java's iteration statements are nearly identical to those found in C and C++ and include for loops, while loops, and do…whileloops.

The for Statement

If Java programmers turn out to be anything like C or C++ programmers, many of them will be partial to the forstatement because of its syntactic elegance. The first line of a for loop enables you to specify a starting value for a loop counter, specify the test condition that will exit the loop, and indicate how the loop counter should be incremented after each pass through the loop. This is definitely a statement that offers a lot of bang for the buck. The syntax of a Java forstatement is as follows:

for (initialization; testExpression; incremement)
    statement
For example, a sample forloop may appear as follows:

int count;
for (count=0; count<100; count++)
    System.out.println("Count = " + count);
In this example, the initialization statement of the forloop sets count to 0. The test expression, count < 100, indicates that the loop should continue as long as countis less than 100. Finally, the increment statement increments the value of countby one. As long as the test expression is true, the statement following the for loop setup will be executed, as follows:
System.out.println("Count = " + count);
Of course, you probably need to do more than one thing inside the loop. This is as easy to do as using curly braces to indicate the scope of the for loop, as shown in the following:

int count;
for (count=0; count<100; count++) {
    YourMethod(count);
    System.out.println("Count = " + count);
}
One nice shortcut that can be taken with a Java forloop is to declare and initialize the variable used in the loop. For example, in the following code, the variable countis declared directly within the forloop:

for (int count=0; count<100; count++) 
    System.out.println("Count = " + count);
It may look like an inconsequential difference whether you declare a variable before a for loop or within the loop. However, there are advantages to declaring the variable within the loop. First, it makes your intention to use the variable within the loop clear. If the variable is declared above the for loop, how will you remember (and how will future programmers know) that the variable was intended for use only within the loop? Second, a variable declared within the for loop will go out of scope at the end of the loop. This means you could not write the following code:

for (int count=0; count<100; count++) 
    System.out.println("Count = " + count);
System.out.println("Loop exited with count = " + count);
The last line cannot find a variable named countbecause count goes out of scope when the for loop terminates. This means that, in addition to making the intended purpose of the variable more clear, it is also impossible to accidentally bypass that intent and use the variable outside the loop.
You can also leave out portions of the first line of a forloop. In the following example, the increment statement has been left out:

for (int count=0; count<100; ) {
    count += 2;
    System.out.println("Count = " + count);
}
Of course, leaving the increment statement out of the forloop declaration in this example doesn't achieve any useful purpose since count is incremented inside the loop.
It is possible to get even fancier with a Java forloop by including multiple statements or conditions. For example, consider the following code:

for (int up=0, down = 20; up < down; up++, down -= 2 ) {
    System.out.println("Up = " + up + "\tDown = " + down);
}
This loop starts the variable upat 0 and increments it by 1. It also starts the variable down at 20and decrements it by 2 for each pass through the loop. The loop continues until uphas been incremented enough that it is equal to or greater than the variable down.
The test expression portion of a Java forloop can be any Boolean expression. Because of this, it does not need to be a simple test (x < 10), as shown in the preceding examples. The test expression can be a method call, a method call combined with a value test, or anything that can be phrased as a Boolean expression. For example, suppose you want to write a method that will display a message indicating the first year since World War II that the Chicago Cubs appeared in the World Series. You could do this as follows:

public boolean DidCubsPlayInWorldSeries(int year) {
    boolean retval;

    switch(year) {
        case 1907:             // these are years the Cubs won
        case 1908:
            retval = true;
            break; 
        case 1906:             // these are years the Cubs lost
        case 1910:
        case 1918:
        case 1929:
        case 1932:
        case 1935:
        case 1938:
        case 1945:
            retval = true;
            break; 
        default:
            retval = false;
    }
    return retval;
}

public void FindFirstAfterWWII() {
    for (int year=1946; DidCubsPlayInWorldSeries(year)==false; year++) {
        System.out.println("The Cubs didn't play in " + year);
    }
}
The method DidCubsPlayInWorldSeriesis passed an integer value indicating the year and returns a Boolean value that indicates whether or not the Cubs made it to the World Series in that year. This method is an example of the switchstatement shown earlier in this chapter.
The method FindFirstAfterWWIIuses a for loop to find a year in which the Cubs played in the World Series. The loop starts year with 1946 and increments year by one for each pass through the loop. The test expression for the loop will allow the loop to continue as long as the method DidCubsPlayInWorldSeriesreturns false. This is a useful example because it shows that a method can be called within the test expression of a forloop. Unfortunately, it is a bad example in that the Cubs haven't won the World Series since the goose step was popular in Berlin, and there is no sign of that changing in the near future. In other words, a loop that looks for a Cubs World Series appearance after 1945 is an infinite loop.

The while Statement

Related to the for loop is the while loop. The syntax for a while loop is as follows:

while (booleanExpression)
    statement
As you can tell from the simplicity of this, the Java whileloop does not have the built-in support for initializing and incrementing variables that its for loop does. Because of this, you need to be careful to initialize loop counters prior to the loop and increment them within the body of the while loop. For example, the following code fragment will display a message five times:

int count = 0;
while (count < 5) {
    System.out.println("Count = " + count);
    count++;
}

The do…while Statement

The final looping construct in Java is the do…whileloop. The syntax for a do…whileloop is as follows:

do {
    statement
} while (booleanExpression);
This is similar to a whileloop except that a do…whileloop is guaranteed to execute at least once. It is possible that a while loop may not execute at all depending on the test expression used in the loop. For example, consider the following method:

public void ShowYears(int year) {
    while (year < 2000) {
        System.out.println("Year is " + year);
        year++;
    }
}

This method is passed a year value, then loops over the year displaying a message as long as the year is less than 2000. If yearstarts at 1996, then messages will be displayed for the years 1996, 1997, 1998, and 1999. However, what happens if yearstarts at 2010? Because the initial test, year < 2000, will be false, the while loop will never be entered. Fortunately, a do…whileloop can solve this problem. Because a do…whileloop performs its expression testing after the body of the loop has executed for each pass, it will always be executed at least once. This is a very valid distinction between the two types of loop, but it can also be a source of potential errors. Whenever you use a do…while loop, you should be careful to consider the first pass through the body of the loop. 

No comments:

Post a Comment