| For loop is a very powerful iteration statement in Java. It is used in most applications where a block of code needs to be execute for N number of times. N range from 1 to max value permitted by any datatype. If it is java int type then max permitted value is [to be filled]. Here is the general form of the for statement:
for(initialization; condition; iteration) {
// body
}
When the loop starts for the first time, the initialization block of the loop is executed. Generally, this code sets the value of the loop control variable which acts as a counter that controls the loop. It is very important that the initialization expression is only executed only once. Next, condition is evaluated which is after the first semi colon in the for loop statment.
for(int i = 0; i < 5; i++)
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 otherwise the loop will be terminated. Next is the iteration portion of the loop that is executed. This portion usually 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. Once controlling expression is false it will not even execute the increment portion of the for loop. It is also very important to remember that the initialization block is executed only for the first time when the program enters into for loop.
There will be times when you will want to include more than one statement in the
initialization and iteration portions of the for loop. This can be achieved using comma. Let us take a very common example
class Example {
public static void main(String args[]) {
int i, j;
j = 5;
for(i=1; i<j; i++) {
System.out.println("i = " + i);
System.out.println("j = " + j);
j--;
}
}
}
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.
class CommaSample {
public static void main(String args[]) {
int i, j;
for(i=1, j=5; i<j; i++, j--) {
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}
}
|