Java for Loop
Java for Loop
The for loop is used when you know exactly how many times you want to repeat a block of code.
It combines initialization, condition, and increment/decrement in one line.
Syntax
Example 1: Print 1 to 5
📌 Output:
Example 2: Print Even Numbers
Example 3: Reverse Countdown
Example 4: Multiplication Table
Example 5: Sum of First 10 Numbers
Example 6: Loop Through an Array
Example 7: Nested for Loop (Pattern Example)
📌 Output:
🧠 When to Use a for Loop?
Use it when:
✔ You know the number of iterations
✔ You want compact control of start, stop, and step values
🔍 while vs for Summary
| Feature | while |
for |
|---|---|---|
| Best for | Unknown iteration count | Known iteration count |
| Structure | Condition only | Init + Condition + Update |
| Readability | Moderate | Very clear |
