Loops: Mastering Repetition
Loops allow you to automate repetitive tasks, such as printing a list, processing items in a collection, or keeping a game running. Java provides three main types of loops.
1. The while Loop
The while loop is the simplest. It repeats as long as its condition is true. Use this when you don't know exactly how many times you need to repeat (e.g., waiting for a user to type "quit").
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++; // Important: increment to avoid an infinite loop!
}
2. The do-while Loop
The do-while loop is a variation of the while loop. The main difference is that it executes the code block once before checking the condition. This guarantees the code runs at least once.
int num = 10;
do {
System.out.println("This will print at least once.");
} while (num < 5);
3. The for Loop
The for loop is the most common. It is best used when you know exactly how many times you want to run the code. It keeps the counter, condition, and increment all in one line.
// (initialization; condition; increment)
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
The Breakdown:
- Initialization (
int i = 0): Sets the starting point. - Condition (
i < 5): The loop runs as long as this is true. - Increment (
i++): Updates the counter after each loop.
4. Loop Control: break and continue
Sometimes you need to exit a loop early or skip a specific turn.
break: Stops the loop immediately.continue: Skips the rest of the current turn and jumps to the next one.
for (int i = 1; i <= 10; i++) {
if (i == 5) continue; // Skip 5
if (i == 8) break; // Stop completely at 8
System.out.println(i);
}
💻 Full Practical Example: The Countdown Timer
Copy this code to see a loop combined with user input:
import java.util.Scanner;
public class Countdown {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number to start the countdown: ");
int start = input.nextInt();
System.out.println("Blast off in...");
while (start > 0) {
System.out.println(start + "...");
start--; // Decrease by 1
}
System.out.println("LIFTOFF! 🚀");
input.close();
}
}
💡 Challenge: The Multiplication Table
Write a program that asks the user for a number (e.g., 5). Use a for loop to print the multiplication table for that number from 1 to 10.
- Output Example:
5 x 1 = 5,5 x 2 = 10...