When the number of repetitions is clear, a for loop is often easier to read than a while loop. It expresses “take values from a sequence one by one” in a single line.
Counting with for
A Java counting loop places initialization, continuation condition, and update in one header, such as for (int i = 0; i < 5; i++).
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 1; i < 10; i += 2) {
System.out.print(i + " ");
}Output:
0 1 2 3 4
10 11 12 13 14
1 3 5 7 9for (initialization; condition; update) initializes once, checks the condition before each iteration, and updates after each iteration.
KNOWLEDGE QUIZ
Fixed-count accumulation
To sum integers from 1 to 100, use for (int i = 1; i <= 100; i++). The condition i <= 100 includes 100.
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
System.out.println(total);Output:
Sum = 5050This version makes the value range of i easier to see than an equivalent while loop.
Step through an accumulating for loop
Run one statement at a time and watch i flow into total.
01int total = 0;02for (int i = 1; i <= 100; i++) {03 total += i;04}05System.out.println(total);
>>>
KNOWLEDGE QUIZ
Fibonacci sequence
The first two Fibonacci numbers are 1, 1. Starting from the third term, each term equals the sum of the previous two terms.
int n = 10;
int first = 1;
int second = 1;
System.out.print(first + " " + second + " ");
for (int i = 3; i <= n; i++) {
int current = first + second;
System.out.print(current + " ");
first = second;
second = current;
}One possible run:
Enter the number of terms: 10
1 1 2 3 5 8 13 21 34 55The most important updates are:
first = second;
second = current;They slide the two-number window forward, so the next loop can keep using the previous two terms.
Slide the Fibonacci window
Each click executes the next assignment. Notice that assignment order matters.
01int first = 1;02int second = 1;03for (int i = 3; i <= 10; i++) {04 int current = first + second;05 first = second;06 second = current;07}
KNOWLEDGE QUIZ
List the leap years in a range
Read a start year and end year, then use a for loop to find every leap year in the interval.
- Read startYear and endYear.
- Iterate over the closed interval and test each year.
- Print all leap years on one line.