Java for Loop
Learn how to repeat code multiple times. The for loop lets you automate repetitive tasks and work with collections of data efficiently.
What is a for Loop?
A for loop repeats a block of code a specific number of times. Instead of writing the same code over and over, you write it once inside a loop and let the computer repeat it. Loops save time and make code cleaner. Think of a for loop like photocopying a document 10 times - you don't write it 10 times, you just set the copier to make 10 copies.
- Automates repetition: Do something many times without writing code multiple times
- Counter-based: Uses a counter to track how many times the loop has run
- Controlled: You specify exactly how many times to repeat
- Efficient: Clean and easy to read code
Think of it this way: Without a loop, printing numbers 1-5 would need 5 print statements. With a for loop, you write one print statement and tell it to repeat 5 times. The loop handles the counting automatically.
for Loop Syntax
Here's the structure of a for loop:
Basic for Loop Structure
for (initialization; condition; increment) {
// Code to repeat goes here
}
Three Parts of a for Loop:
- Initialization: Create and set the starting value of the counter (usually int i = 0)
- Condition: Check if the counter meets a condition (usually i < 10). If true, loop runs. If false, loop stops.
- Increment: Increase the counter each time (usually i++ which means i = i + 1)
Example breakdown: for (int i = 0; i < 5; i++)
• Start: i is 0
• Repeat while: i is less than 5
• After each repeat: Add 1 to i
Simple for Loop Examples
Let's see the for loop in action with real examples:
Example 1: Print Numbers 1 to 5
public class PrintNumbers {
public static void main(String[] args) {
System.out.println("Printing numbers 1 to 5:");
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
System.out.println("Loop finished!");
}
}
Printing numbers 1 to 5: Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Loop finished!
Step-by-step:
- int i = 1: Counter i starts at 1
- i <= 5: Loop runs while i is less than or equal to 5
- i++: After each run, i increases by 1
- Iterations: i = 1, 2, 3, 4, 5, then condition becomes false and loop stops
Example 2: Print Even Numbers
public class EvenNumbers {
public static void main(String[] args) {
System.out.println("Even numbers from 2 to 10:");
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
}
}
Even numbers from 2 to 10: 2 4 6 8 10
What's different:
- i = 2: Start at 2 instead of 1
- i += 2: Add 2 to i each time instead of just 1
- This prints every second number: 2, 4, 6, 8, 10
Example 3: Counting Backwards
public class CountBackwards {
public static void main(String[] args) {
System.out.println("Countdown from 5 to 1:");
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Blastoff!");
}
}
Countdown from 5 to 1: 5 4 3 2 1 Blastoff!
What's different:
- i = 5: Start from 5
- i >= 1: Continue while i is greater than or equal to 1
- i--: Decrease i by 1 each time
- This counts down from 5 to 1
Using for Loops with Calculations
Example 1: Calculate Sum (1 + 2 + 3 + ... + 10)
public class CalculateSum {
public static void main(String[] args) {
int sum = 0;
System.out.println("Calculating sum of 1 to 10:");
for (int i = 1; i <= 10; i++) {
sum = sum + i; // Add each number to sum
System.out.println("i = " + i + ", sum so far = " + sum);
}
System.out.println("\nTotal sum: " + sum);
}
}
Calculating sum of 1 to 10:
i = 1, sum so far = 1
i = 2, sum so far = 3
i = 3, sum so far = 6
i = 4, sum so far = 10
i = 5, sum so far = 15
i = 6, sum so far = 21
i = 7, sum so far = 28
i = 8, sum so far = 36
i = 9, sum so far = 45
i = 10, sum so far = 55
Total sum: 55
How it works:
- sum = 0: Start with sum as 0
- Each loop iteration: Add the current number i to sum
- After 10 iterations: All numbers 1-10 are added together: 1+2+3+...+10 = 55
- This shows how to accumulate values in a loop
Example 2: Calculate Multiplication Table
public class MultiplicationTable {
public static void main(String[] args) {
int number = 5;
System.out.println("Multiplication table of " + number + ":");
System.out.println();
for (int i = 1; i <= 10; i++) {
int result = number * i;
System.out.println(number + " x " + i + " = " + result);
}
}
}
Multiplication table of 5: 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
Real-world use: This demonstrates how loops make generating tables easy. Without a loop, you'd need to write 10 multiplication statements!
for Loop with Arrays
for loops are perfect for working with arrays. You can easily go through each element and process it.
Example 1: Print Array Elements
public class PrintArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Array elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at position " + i + " is: " + numbers[i]);
}
}
}
Array elements: Element at position 0 is: 10 Element at position 1 is: 20 Element at position 2 is: 30 Element at position 3 is: 40 Element at position 4 is: 50
Important concepts:
- i = 0: Arrays start at position 0, not 1
- i < numbers.length: Use .length to get array size (5 in this case)
- numbers[i]: Access array element at position i
- Loop automatically handles going through each element
Example 2: Calculate Average of Array Values
public class ArrayAverage {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 95, 88};
int sum = 0;
// Calculate sum
for (int i = 0; i < scores.length; i++) {
sum = sum + scores[i];
}
// Calculate average
double average = (double) sum / scores.length;
System.out.println("Scores: ");
for (int i = 0; i < scores.length; i++) {
System.out.println(" Score " + (i + 1) + ": " + scores[i]);
}
System.out.println("\nSum of all scores: " + sum);
System.out.println("Average score: " + average);
}
}
Scores: Score 1: 85 Score 2: 92 Score 3: 78 Score 4: 95 Score 5: 88 Sum of all scores: 438 Average score: 87.6
How it works:
- First loop: Adds all scores together
- Calculate: average = sum / number of elements
- Second loop: Prints each score with nice formatting
- This is a real-world use: processing data from an array
Enhanced for Loop (for-each)
Java also has an enhanced for loop (also called for-each) that's simpler when you just need to go through each element. It automatically handles the counter and doesn't need .length.
Syntax: Enhanced for Loop
for (type variableName : array) {
// code runs for each element
}
Breakdown:
- type: The data type of array elements (int, String, etc.)
- variableName: Variable that holds current element (use any name you like)
- array: The array to loop through
Example: Enhanced for Loop
public class EnhancedForLoop {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
System.out.println("Fruits:");
// Using enhanced for loop
for (String fruit : fruits) {
System.out.println(" - " + fruit);
}
// Compare with regular for loop
System.out.println("\nUsing regular for loop:");
for (int i = 0; i < fruits.length; i++) {
System.out.println(" - " + fruits[i]);
}
}
}
Fruits: - Apple - Banana - Orange - Mango Using regular for loop: - Apple - Banana - Orange - Mango
Comparison:
- Enhanced for: Simpler, cleaner, no index needed
- Regular for: More control, can use index if needed
- Use enhanced for when you just want each element
- Use regular for when you need the position/index
When to use each:
Regular for: When you need the index (i)
Enhanced for: When you just need the element value
Nested for Loops
You can put a for loop inside another for loop. This is called nesting and is useful for working with 2D data or creating patterns.
Example 1: Print a Grid Pattern
public class GridPattern {
public static void main(String[] args) {
System.out.println("3x3 Grid:");
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("* ");
}
System.out.println(); // New line after each row
}
}
}
3x3 Grid: * * * * * * * * *
How nested loops work:
- Outer loop: row goes from 1 to 3
- Inner loop: For each row, col goes from 1 to 3
- Each iteration of outer loop runs inner loop completely
- Inner loop finishes before outer loop continues
Example 2: Multiplication Table Grid
public class MultiplicationGrid {
public static void main(String[] args) {
System.out.println("Multiplication Table (1-5):");
System.out.println();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
int result = i * j;
System.out.print(result + "\t"); // \t for tab spacing
}
System.out.println(); // New line
}
}
}
Multiplication Table (1-5): 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Real-world use: Creating tables, grids, or any 2D data structure. The outer loop handles rows and inner loop handles columns.
Important: Nested loops can get expensive! With outer loop 100 times and inner loop 100 times, code inside inner loop runs 10,000 times. Be careful with nested loops.
Common Mistakes to Avoid
Mistake 1: Off-by-One Error
// WRONG: Prints 0-4 instead of 1-5
for (int i = 0; i < 5; i++) {
System.out.println(i); // Prints 0, 1, 2, 3, 4
}
// CORRECT: Prints 1-5
for (int i = 1; i <= 5; i++) {
System.out.println(i); // Prints 1, 2, 3, 4, 5
}
// ALSO CORRECT: Prints 1-5
for (int i = 0; i < 5; i++) {
System.out.println(i + 1); // Prints 1, 2, 3, 4, 5
}
Explanation: Carefully think about where your loop should start and end. Remember arrays start at 0!
Mistake 2: Infinite Loop
// WRONG: i++ never happens, infinite loop!
for (int i = 0; i < 10; i) {
System.out.println(i);
}
// CORRECT: i++ is included
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
// ANOTHER WRONG: Condition is always true
for (int i = 0; i >= 0; i++) { // i is always >= 0!
System.out.println(i); // Infinite loop!
}
Explanation: Always include the increment (i++) and make sure the condition can become false.
Mistake 3: Array Index Out of Bounds
int[] numbers = {10, 20, 30}; // Array has 3 elements (indices 0, 1, 2)
// WRONG: i goes up to 3, but index 3 doesn't exist!
for (int i = 0; i <= 3; i++) {
System.out.println(numbers[i]); // Error when i = 3
}
// CORRECT: Use i < numbers.length
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]); // Safe, goes 0, 1, 2
}
Explanation: Arrays are 0-indexed. If array has length 3, valid indices are 0, 1, 2. Use < numbers.length, not <= numbers.length.
Summary of Common Mistakes:
1. Off-by-one: Wrong starting or ending value
2. Infinite loop: Increment missing or condition never becomes false
3. Array out of bounds: Using wrong loop limits with arrays