Java For Loop
Repeating code execution with controlled iterations
🔄 What is a For Loop?
A for loop in Java repeats a block of code a specific number of times. It's perfect when you know exactly how many times you want to execute code, making repetitive tasks simple and efficient.
// Simple for loop example
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
For Loop Structure
Initialization
Set starting value for counter
int i = 0
Condition
Check if loop should continue
i < 10
Update
Change counter after each iteration
i++
Body
Code to execute each time
System.out.println(i);
🔹 Basic For Loop Syntax
The for loop has three parts separated by semicolons:
for (initialization; condition; update) {
// Code to execute
}
// Example: Print numbers 1 to 3
for (int i = 1; i <= 3; i++) {
System.out.println("Number: " + i);
}
Output:
Number: 1 Number: 2 Number: 3
🔹 Counting Backwards
You can also count backwards by decreasing the counter:
// Countdown from 5 to 1
for (int i = 5; i >= 1; i--) {
System.out.println("Countdown: " + i);
}
System.out.println("Blast off!");
Output:
Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Blast off!
🔹 Different Step Sizes
You can increment by any number, not just 1:
// Count by 2s
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even number: " + i);
}
// Count by 5s
for (int i = 5; i <= 25; i += 5) {
System.out.println("Multiple of 5: " + i);
}
Output:
Even number: 0 Even number: 2 Even number: 4 Even number: 6 Even number: 8 Even number: 10 Multiple of 5: 5 Multiple of 5: 10 Multiple of 5: 15 Multiple of 5: 20 Multiple of 5: 25
🔹 Practical Examples
Here are some useful for loop examples:
🔸 Sum of Numbers
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
System.out.println("Adding " + i + ", sum is now: " + sum);
}
System.out.println("Final sum: " + sum);
Output:
Adding 1, sum is now: 1 Adding 2, sum is now: 3 Adding 3, sum is now: 6 Adding 4, sum is now: 10 Adding 5, sum is now: 15 Final sum: 15
🔸 Multiplication Table
int number = 3;
System.out.println("Multiplication table for " + number + ":");
for (int i = 1; i <= 5; i++) {
int result = number * i;
System.out.println(number + " x " + i + " = " + result);
}
Output:
Multiplication table for 3: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15