|
You may face a situation in programming where you need to repeat the execution of statement for a fixed number of times. You can achieve this with a while loop by setting a variable and incrementing it over a range of values. However a more convenient way is to use the for statement. In the following code, a simple for loop prints numbers from 1 to 10:
for(int i=1;i<=10;i++) {
System.out.println(i);
}
The general format of for loop is:
for(initialization; condition; step) {
[Statements;]
}
Instead of specifying just the condition, the for loop has three main parts:
initialization This is the first part of the for statement. It lets you declare and initialize zero or more variables of the same type. The initialization takes place just once at the very beginning of the for loop execution. Usually you define the variables used for stepping through the for loop. You may also define any local variable to be used within the for loop’s block.
condition It is the middle part of the for statement. You specify the condition in the form of a boolean expression. Similar to the while and do-while loop, this expression must be evaluated to a value of boolean type. The condition is checked at the start of every iteration of the for loop. If the condition is true then the statements within the for block are executed.
step The third part is executed after each execution of the body of the for loop. Here you specify what you want to do after every iteration of the loop. Usually the variable used for stepping is either incremented or decremented here. However, you can use any valid Java statement here.
The for statement is a little bit more complex than the other two iterative statements because it specifies the condition, stepping and initialization all in one place. Moreover, these three things happen at different times during the execution. For instance, initialization happens only once whereas condition-check and stepping occurs for each iteration. The following sections discuss the details of these sections with examples.
|
|
For the exam, you need to understand how the for loop works in order to guess the output by looking at the code. For that, you must know the order in which initialization, condition-check and stepping take place. |
Multiple statements in the initialization and step parts
The variables declared in the initialization part of the for loop are local variables. They are initialized once at the beginning of for loop’s execution. These variables are accessible only within the block of the for loop. The following code does not compile as it tries to access the for block’s local variables outside the block:
for(int i=1,j=5;i<=10;i++) {
System.out.println(i);
}
System.out.println(i); // Compiler Error!
System.out.println(j); // Compiler Error!
In the above example, we have 2 variables i and j declared and initialized in the for statement. You can define multiple variables in the initialization part separating them by comma. Similarly, you can specify multiple statements as steps separated by comma in the third part. In the following example, both i and j are incremented in the third part of for loop.
for(int i=1,j=5;j<=10;i++,j++) {
System.out.println(i);
System.out.println(j);
}
You can declare and initialize multiple variables as well as specify multiple steps. However, you cannot give multiple conditions in the for loop. The code below will not compile, as there can be only one condition in for loop:
for(int i=1,j=5; i<4,j<=10;i++,j++) { //compiler error!
System.out.println(i);
System.out.println(j);
}
Though there can be only one condition in for loop, you can always write a compound condition using logical operators (& | ^ ) or the short-circuit operators (&& ||). These operators operate on boolean values and return boolean value. Therefore, you can use them to specify the end condition of the for loop. For instance, following code is valid:
for(int i=1,j=5; i<4 && j<=10;i++,j++) { // valid condition
System.out.println(i);
System.out.println(j);
}
(i<4 && j<=10) returns true when both conditions (i<4 and j<=10) are true. We will learn more about operators in chapter 9. You can use the comparison and logical operators to specify the condition in the if statements.
Optional parts in the for statement
All the three parts in the for loop are optional except the semicolons. Therefore the following code is perfectly valid. There is no condition specified, therefore it is assumed as true. Hence, this loop will execute infinitely.
for (;;) {
System.out.println("This is an infinite loop");
}
You can also give just the first or the second of the three parts of a for statement. In the following example, we are specifying only the condition and the step within the for statement. The initialization is done outside, just before the for statement.
int i = 0;
for (; i < 6; i = i + 2) {}
Stepping through the for loop
The step statement is executed after each execution of the body of the for loop. You can think of it as the last statement to be executed after everything in the for block is executed for each iteration. If a condition is not true, neither the for block nor the step statement is executed. In the following code, when the value of i becomes 6, it does not satisfy the condition anymore. Therefore nothing is executed within the block for i=6 and the stepping i = i + 2 is not executed either.
int i = 0;
for (; i < 6; i = i + 2) {
// do something
}
System.out.println(i); // 6 is printed
The control just comes out of the for loop at i=6. After the loop, it prints 6 as the value of i and not the value 8.