Java Loops: for Loop
On Day 9, we learn the for loop. A for
loop is commonly used when you know how many times you want to repeat a block of code. It has three parts: initialization, condition, and update.
1. Syntax of for Loop
for (initialization; condition; update) {
// code block
}
How it works: The loop starts by running the initialization once, then checks the condition. If true, it executes the block, updates the variable, and checks again.
2. Example: Counting from 1 to 5
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
Explanation: The loop starts at i = 1
, prints, then increments until i = 5
. When i
becomes 6, the condition is false, and the loop stops.
3. Example: Reverse Counting
public class ReverseForLoop {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
System.out.println("Countdown: " + i);
}
}
}
Explanation: Here, i
starts at 5 and decreases by 1 each time until it reaches 1.
4. Example: Printing Even Numbers
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
}
}
Explanation: Starting at 2, the loop adds 2 each time, printing 2, 4, 6, 8, 10.
Summary
The for
loop is ideal when the number of iterations is known. It keeps initialization, condition, and update in one line, making code compact and readable.