The second type of loop that we will learn is the for loop. The for loop allows us to simplify some while loops. Although for loops can be used for any while loop, they are mostly used when the number of repetitions is fixed. The most important part of the for loop is the for loop header, where there is a variable initialization, a conditional expression, and an incrementer (decrements work here too!) Here is the for loop's anatomy for the "fixed number of repetitions" situation:
for (int i = 0; i < numberOfTimesToRepeat; i++) {
thing to be repeated
}
The initialization is the int i = 0
, the conditional expression is the i < numberOfTimesToRepeat
, and the incrementer is the i++
. The initialization is done before the loop itself runs, and the incrementer is done at the end of the iteration and before the next. As with while loops, the conditional expression determines when the loop stops.
All for loops can be converted into while loops. For the loop structure above, here would be how we do it:
int i = 0;
while (i < numberOfTimesToRepeat) {
thing to be repeated
i++;
}
As we can see, these both do the same thing, but what takes the while loop 5 lines can be simplified to 3 lines in the for loop. For example, here is code that prints the first 10 even numbers as both a for loop and a while loop:
for (int i = 0; i < 10; i++) {
System.out.println(i * 2);
}
int j = 0;
while (j < 10) {
System.out.println(j * 2);
j++;
}
For loops are used for situations where code is run for a fixed number of times. On the other hand, while loops run until a condition is met but don't know when this will happen or how many tries it will take for the loop to exit. For loops are more concise in situations where they can be used, but for loops and while loops for the same situation will take the same time to run. However, while loops in the end are more versatile than for loops with more uses. If there is a situation involving loops that you don't know how to implement at first, first try using while loops, and when you have your solution, see if you can implement it as a for loop.
In Unit 6 and 7, we will learn another important application of for loops β to traverse arrays and ArrayLists.
Using for loops, we can make a program that prints out the first n Fibonacci numbers as follows:
public static void printNFibonacci(int n) {
int a = 0;
int b = 1;
for (int i = 0; i < n; i++) {
fib = a + b;
a = b;
b = fib;
System.out.println(fib);
}
}