Loops (For, While)
Overview
Computers are amazing at doing repetitive tasks instantly. If you wanted to print 'Hello' 100 times, you wouldn't write `System.out.println("Hello")` 100 times. You would use a Loop.
Loops allow you to run the same block of code multiple times. There are two main types: `for` loops (used when you know EXACTLY how many times to repeat) and `while` loops (used when you want to repeat UNTIL a condition becomes false).
1. The 'For' Loop
Best when you know the count. It has 3 parts: Initialization (where to start), Condition (when to stop), and Increment (how much to step by).
2. The 'While' Loop
Best when you don't know the exact count. It just keeps looping as long as its condition is true. It's like saying 'Keep running *while* the battery is > 0'.
3. Infinite Loops (Danger!)
If your loop's condition never becomes false, the loop will run forever until your program crashes. Always make sure you are updating your variables inside the loop!
Syntax
Starts at i=1, runs as long as i<=5, and i increases by 1 each time.
// Initialization ; Condition ; Increment
for (int i = 1; i <= 5; i++) {
System.out.println("Pushup number: " + i);
}
// Output: Pushup 1, Pushup 2... up to 5.You must manually update the condition variable inside the loop.
int battery = 3;
while (battery > 0) {
System.out.println("Phone is on. Battery: " + battery);
battery--; // Decrease battery by 1
}
System.out.println("Phone died.");Common Pitfalls
- Infinite Loops! Forgetting to write `i++` in a for-loop, or forgetting to decrease the battery in a while-loop. Your code will freeze forever.
Interview Tips
- Always double-check your loop boundaries. A very common mistake is 'Off-by-one' errors (e.g., looping 11 times instead of 10 because you used `<=` instead of `<`).
Real-World Example
Loops are heavily used for processing large amounts of data or keeping a game running.
public class GameLoop {
public static void main(String[] args) {
boolean isGameOver = false;
int score = 0;
// The core game loop that keeps the game running
while (!isGameOver) {
score += 10;
System.out.println("Playing... Score: " + score);
if (score >= 30) {
isGameOver = true; // Ends the loop
System.out.println("You won!");
}
}
}
}