for Loop (Java)
A for loop repeats a block of code a set number of times. It has three parts in its header: initialization, a condition, and an update, all separated by semicolons.
Java
The loop runs while the condition stays true, updating the counter each pass. Java also has an enhanced 'for-each' loop (for (int n : nums)) that iterates directly over the items in an array or collection.
for loops are ideal when you know how many times you want to repeat something.
Examples
Java
for (int i = 0; i < 3; i++) {
System.out.println(i);
}Output:
0
1
2Java — Enhanced 'for-each' loop over an array.
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}Output:
10
20
30