What is a For Loop?
A for loop repeats a block of code a known number of times. It's the most commonly used loop when you know in advance how many iterations are needed.
java
for (initialization; condition; update) {
// Code to execute in each iteration
}| Part | Purpose | Example |
|---|---|---|
| Initialization | Set up loop variable | int i = 0 |
| Condition | Check before each iteration | i < 10 |
| Update | Execute after each iteration | i++ |
Basic For Loop
java
public class ForLoopBasic {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5How it executes step by step:
| Step | i | Condition i <= 5 | Action |
|---|---|---|---|
| 1 | 1 | true | Print, then i++ |
| 2 | 2 | true | Print, then i++ |
| 3 | 3 | true | Print, then i++ |
| 4 | 4 | true | Print, then i++ |
| 5 | 5 | true | Print, then i++ |
| 6 | 6 | false | Loop ends |
Common For Loop Patterns
Counting Forward
java
// 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
// Output: 1 2 3 4 5 6 7 8 9 10Counting Backward
java
// 10 to 1
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
// Output: 10 9 8 7 6 5 4 3 2 1Stepping by 2 (Even Numbers)
java
for (int i = 2; i <= 20; i += 2) {
System.out.print(i + " ");
}
// Output: 2 4 6 8 10 12 14 16 18 20Iterating Over an Array
java
int[] scores = {85, 92, 78, 95, 88};
for (int i = 0; i < scores.length; i++) {
System.out.println("Student " + (i + 1) + ": " + scores[i]);
}Output:
Student 1: 85
Student 2: 92
Student 3: 78
Student 4: 95
Student 5: 88Enhanced For Loop (For-Each)
The for-each loop simplifies iterating over arrays and collections when you don't need the index:
java
// Syntax: for (dataType element : collection) { }
String[] fruits = {"Apple", "Mango", "Banana", "Grapes"};
for (String fruit : fruits) {
System.out.println("I like " + fruit);
}Output:
I like Apple
I like Mango
I like Banana
I like GrapesFor Loop vs For-Each
java
int[] numbers = {10, 20, 30, 40, 50};
// Traditional for — when you need the index
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
// For-each — when you only need the value
for (int num : numbers) {
System.out.println("Value: " + num);
}| Feature | for loop | for-each loop |
|---|---|---|
| Access index | ✓ Yes | ✗ No |
| Modify elements | ✓ Yes | ✗ No (copy only) |
| Cleaner syntax | — | ✓ Yes |
| Use with Collections | ✓ Yes | ✓ Yes |
Nested For Loops
A loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Multiplication Table
java
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
}Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50Star Pattern
java
public class StarPattern {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}Output:
*
* *
* * *
* * * *
* * * * *Loop Control: break and continue
break — Exit the Loop Early
java
// Find the first negative number
int[] numbers = {5, 12, -3, 8, -7, 15};
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] < 0) {
System.out.println("First negative number: " + numbers[i] + " at index " + i);
break; // Stop the loop immediately
}
}Output:
First negative number: -3 at index 2continue — Skip Current Iteration
java
// Print only even numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // Skip odd numbers
}
System.out.print(i + " ");
}
// Output: 2 4 6 8 10Labeled Break (for Nested Loops)
java
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer; // Breaks out of BOTH loops
}
System.out.println("i=" + i + ", j=" + j);
}
}Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1Infinite For Loop
A loop without a condition runs forever (use with caution):
java
// Intentional infinite loop (e.g., game loop, server)
for (;;) {
System.out.println("Running...");
// Must have a break condition!
break;
}Practical Example: Student Report Card
java
import java.util.Scanner;
public class ReportCard {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] subjects = {"Mathematics", "Physics", "Chemistry", "English", "Computer Science"};
int[] marks = new int[subjects.length];
int total = 0;
// Input marks
System.out.println("=== Enter Marks (out of 100) ===");
for (int i = 0; i < subjects.length; i++) {
System.out.print(subjects[i] + ": ");
marks[i] = scanner.nextInt();
total += marks[i];
}
// Display report
System.out.println("\n=== Report Card ===");
System.out.printf("%-20s %s%n", "Subject", "Marks");
System.out.println("─".repeat(30));
for (int i = 0; i < subjects.length; i++) {
String status = (marks[i] >= 40) ? "Pass" : "Fail";
System.out.printf("%-20s %d (%s)%n", subjects[i], marks[i], status);
}
System.out.println("─".repeat(30));
double percentage = (double) total / (subjects.length * 100) * 100;
System.out.printf("Total: %d / %d%n", total, subjects.length * 100);
System.out.printf("Percentage: %.1f%%%n", percentage);
// Determine grade using for loop
String[] grades = {"A+", "A", "B", "C", "D", "F"};
int[] cutoffs = {90, 80, 70, 60, 50, 0};
String grade = "F";
for (int i = 0; i < cutoffs.length; i++) {
if (percentage >= cutoffs[i]) {
grade = grades[i];
break;
}
}
System.out.println("Grade: " + grade);
scanner.close();
}
}Sample Output:
=== Enter Marks (out of 100) ===
Mathematics: 85
Physics: 78
Chemistry: 92
English: 88
Computer Science: 95
=== Report Card ===
Subject Marks
──────────────────────────────
Mathematics 85 (Pass)
Physics 78 (Pass)
Chemistry 92 (Pass)
English 88 (Pass)
Computer Science 95 (Pass)
──────────────────────────────
Total: 438 / 500
Percentage: 87.6%
Grade: ASummary
- The
forloop has three parts: initialization, condition, and update - Use the for-each loop for simple iteration over arrays and collections
- Nested loops run the inner loop completely for each outer iteration
breakexits the loop early;continueskips to the next iteration- Use labeled break to exit outer loops from nested loops
- The for loop is ideal when the number of iterations is known in advance
- Always ensure the loop condition will eventually become
falseto avoid infinite loops