The for-with-index loop
The for-with-index loop gives you more control over the loop, at the cost of being more complex. We define it as:
for ( initializer ; condition ; incrementor ) {
body
}
where:
- condition is a boolean expression;
- body is zero or more statements;
- The for loop executes the code in body as long as the condition expression evaluates to true;
- initializer is a statement that is executed once, at the beginning of the loop;
- incrementor is a statement that is executed after each execution of body.
The names “initializer” and “incrementor” were chosen to reflect the typical role of these statements, but the statements don't need to initialize or increment anything; that's just what you usually use them for.
Here is an indexed version of the previous for loop:
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.println(word);
}
The generality of the for-with-index loop allows you to do a wide range of things, but typically you use this kind of for loop when you need to keep track of the index of the array element of the current iteration of the loop, or you want to iterate differently than the for-each loop does. Suppose you want to print the words in reverse order:
for (int i = words.length - 1; i >= 0; i--) {
String word = words[i];
System.out.println(word);
}
Or suppose you want to print every third word:
for (int i = 0; i < words.length; i += 3) {
String word = words[i];
System.out.println(word);
}