1. Basic for loop
Initialization runs once, the condition is checked before every iteration, and the update runs after the loop body.
for (int i = 2; i <= 10; i += 2) {
System.out.print(i + " " );
}
// 2 4 6 8 10
Initialization runs once, the condition is checked before every iteration, and the update runs after the loop body.
for (int i = 2; i <= 10; i += 2) {
System.out.print(i + " " );
}
// 2 4 6 8 10
Use for-each when you need every element and do not need its index.
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.print(number + " " );
}
// 1 2 3 4 5
Java permits more than one initializer and update expression. Keep the condition clear.
for (int i = 0, j = 10; i < 5 && j > 0; i++, j--) {
System.out.println("i=" + i + ", j=" + j);
}
An omitted condition is always true. Provide a safe break, cancellation, or shutdown condition.
for (;;) {
// Repeats until break, return, or process termination.
}
The inner loop completes for each outer-loop iteration. This is useful for matrices and patterns.
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
System.out.print(row * column + " " );
}
System.out.println();
}
Adjust the update expression to skip values or count backwards.
for (int i = 0; i < 10; i += 2) {
System.out.print(i + " " );
}
// 0 2 4 6 8
When studying this topic, always ask: how much time does it take, how much memory does it use and how does performance change as input size grows?
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " " );
}
System.out.println();
}
}
// Output: 1 2 3 4 5
Change the loop to print the even numbers from 2 through 10. Then rewrite it as a for-each loop over an integer array.
Which statement is correct?