Sunday, November 9, 2008

For Loops

For

You were introduced to a simple form of the for loop in previous posts. As you will see, it is a powerful and versatile construct. Here is the general form of the for statement:

 

for(initialization; condition; iteration)

{

// body

}

 

          If only one statement is being repeated, there is no need for the curly braces.

 

        The for loop operates as follows. When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. It is important to understand that the initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

 

        Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false. Here is a version of the "tick" program that uses a for loop:

LANGUAGE

// Demonstrate the for loop.

class ForTick {

public static void main(String args[]) {

int n;

for(n=10; n>0; n--)

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

}

}

 

        Declaring Loop Control Variables Inside the for Loop Often the variable that controls a for loop is only needed for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For example, here is the preceding program recoded so that the loop control variable n is declared as an int inside the for:

 

// Declare a loop control variable inside the for.

class ForTick {

public static void main(String args[]) {

// here, n is declared inside of the for loop

for(int n=10; n>0; n--)

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

}

}

 

When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) Outside the for loop, the variable will cease to exist. If you need to use the loop control variable elsewhere in your program, you will not be able to declare it inside the for loop.

 

When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i, is declared inside  the for since it is not needed elsewhere.

 

// Test for primes.

class FindPrime {

public static void main(String args[]) {

int num;

boolean isPrime = true;

num = 14;

for(int i=2; i <= num/2; i++) {

if((num % i) == 0) {

isPrime = false;

break;

}

}

if(isPrime) System.out.println("Prime");

else System.out.println("Not Prime");

}

}

 

Using the Comma

There will be times when you will want to include more than one statement in the initialisation and iteration portions of the for loop.

 

For example, consider the loop in the following program:

 

class Sample {

public static void main(String args[]) {

int a, b;

b = 4;

for(a=1; a<b; a++) {

System.out.println("a = " + a);

System.out.println("b = " + b);

b--;

}

}

}

 

As you can see, the loop is controlled by the interaction of two variables. Since the loop is governed by two variables, it would be useful if both could be included in the for statement, itself, instead of b being handled manually. Fortunately, Java provides a way to accomplish this. To allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma.

 

Using the comma, the preceding for loop can be more efficiently coded as shown here:

 

// Using the comma.

class Comma {

public static void main(String args[]) {

int a, b;

for(a=1, b=4; a<b; a++, b--) {

System.out.println("a = " + a);

System.out.println("b = " + b);

}

}

}

 

In this example, the initialization portion sets the values of both a and b. The two comma-separated statements in the iteration portion are executed each time the loop repeats.

 

The program generates the following output:

a = 1

b = 4

a = 2

b = 3

 

If you are familiar with C/C++, then you know that in those languages the comma is an operator that can be used in any valid expression. However, this is not the case with Java. In Java, the comma is a separator that applies only to the for loop.

 

Some for Loop Variations

The for loop supports a number of variations that increase its power and applicability. The reason it is so flexible is that its three parts, the initialization, the conditional test, and the iteration, do not need to be used for only those purposes. In fact, the three sections of the for can be used for any purpose you desire. Let's look at some examples. One of the most common variations involves the conditional expression. Specifically, this expression does not need to test the loop control variable against some target value.

 

In fact, the condition controlling the for can be any Boolean expression.

 

For example, consider the following fragment:

 

boolean done = false;

for(int i=1; !done; i++) {

// ...

if(interrupted()) done = true;

}

 

In this example, the for loop continues to run until the boolean variable done is set to true. It does not test the value of i. Here is another interesting for loop variation. Either the initialization or the iteration expression or both may be absent, as in this next program:

 

// Parts of the for loop can be empty.

class ForVar {

public static void main(String args[]) {

int i;

boolean done = false;

i = 0;

for( ; !done; ) {

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

if(i == 10) done = true;

i++;

}

}

}

 

Here, the initialization and iteration expressions have been moved out of the for. Thus, parts of the for are empty. While this is of no value in this simple example-indeed, it would be considered quite poor style—there can be times when this type of approach makes sense. For example, if the initial condition is set through a complex expression elsewhere in the program or if the loop control variable changes in a non-sequential manner determined by actions that occur within the body of the loop, it may be appropriate to leave these parts of the for empty. Here is one more for loop variation. You can intentionally create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty.

 

For example:

 

for( ; ; )

{

// ...

}

 

This loop will run forever, because there is no condition under which it will terminate. Although there are some programs, such as operating system command processors, that require an infinite loop, most "infinite loops" are really just loops with special termination requirements. As you will soon see, there is a way to terminate a loop even an infinite loop like the one shown—that does not make use of the normal loop conditional expression.

 

Nested Loops

Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another.

 

For example, here is a program that nests for loops:

 

// Loops may be nested.

class Nested {

public static void main(String args[]) {

int i, j;

for(i=0; i<10; i++) {

for(j=i; j<10; j++)

System.out.print(".");

System.out.println();

}

}

}

 

The output produced by this program is shown here:

..........

.........

........

.......

......

.....

....

...

..

.

No comments: