Java For Loop — Counting, Iterating & Enhanced For-Each
Loops let you repeat a block of code multiple times. The for loop is the most commonly used loop when you know how many times to repeat.
The Classic for Loop
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Anatomy
for (initialization; condition; update) {
// body
}
| Part | Purpose | Example |
|---|---|---|
| Initialization | Runs once before the loop | int i = 0 |
| Condition | Checked before each iteration | i < 5 |
| Update | Runs after each iteration | i++ |
Execution Flow
- Initialize → 2. Check condition → 3. Execute body → 4. Update → back to 2.
Counting Examples
// Count 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
// 1 2 3 4 5 6 7 8 9 10
// Count down
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
// 10 9 8 7 6 5 4 3 2 1
// Step by 2
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " ");
}
// 0 2 4 6 8 10
Enhanced For-Each Loop
For iterating over arrays and collections:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Output:
Apple
Banana
Cherry
Syntax: for (Type variable : collection) { ... }
Use for-each when you don’t need the index. It’s cleaner and less error-prone.
When You Need the Index
String[] fruits = {"Apple", "Banana", "Cherry"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(i + ": " + fruits[i]);
}
Nested Loops
A loop inside a loop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print("(" + i + "," + j + ") ");
}
System.out.println();
}
Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
Multiplication Table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
Triangle Pattern
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
Common Patterns
Sum of Numbers
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum); // 5050
Finding Maximum
int[] numbers = {23, 1, 56, 12, 89, 34};
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Max: " + max); // 89
Fibonacci Sequence
int n = 10, a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int temp = a + b;
a = b;
b = temp;
}
// 0 1 1 2 3 5 8 13 21 34
Infinite Loop
for (;;) {
// runs forever — use break to exit
}
Multiple Variables in a For Loop
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i=" + i + " j=" + j);
}
Common Mistakes
Off-By-One Errors
// Prints 0 to 9 (10 iterations)
for (int i = 0; i < 10; i++) { }
// Prints 0 to 10 (11 iterations!)
for (int i = 0; i <= 10; i++) { }
// Prints 1 to 10 (10 iterations)
for (int i = 1; i <= 10; i++) { }
Modifying Collection During For-Each
List<String> names = new ArrayList<>(List.of("A", "B", "C"));
// WRONG — ConcurrentModificationException
for (String name : names) {
names.remove(name);
}
// Use iterator or removeIf instead
names.removeIf(name -> name.equals("B"));
Quick Exercises
- Print all even numbers from 2 to 50.
- Calculate the factorial of 10 using a for loop.
- Print a right-aligned triangle pattern of
*with 5 rows. - Find the sum of all odd numbers between 1 and 100.
Summary
| Loop Type | Use When |
|---|---|
for (init; cond; update) |
Known number of iterations |
for (Type x : collection) |
Iterating all elements |
| Nested loops | Multi-dimensional patterns |
What’s Next?
The for loop is great when you know the count. But sometimes you need to repeat until a condition changes — that’s the while loop: While Loop.