Lesson 12: Iteration: for, while, and do-while Loops
Loops allow you to repeatedly execute a block of code until a certain condition is met.
1. The for Loop
Ideal when you know exactly how many times you need to iterate (e.g., looping through an array).
Structure: for (initialization; condition; update) { ... }
java // Print numbers from 1 to 5 for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); }
Enhanced for Loop (For-Each)
Used for iterating over arrays or collections easily, without needing an index.
java String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) { System.out.println(fruit); }
2. The while Loop
Executes a block of code as long as the specified condition is true. Ideal when the number of iterations is unknown beforehand.
java int counter = 0; while (counter < 3) { System.out.println("Running..."); counter++; } // Important: Ensure the condition eventually becomes false to avoid an infinite loop.
3. The do-while Loop
Similar to while, but guarantees that the loop body executes at least once, because the condition is checked at the end.
java int input = 0; do { System.out.println("Please enter a number greater than 10:"); // Assume we read input here (e.g., using Scanner) // For demonstration, we'll set it to 15 after the first run if (input == 0) input = 15; } while (input < 10);
System.out.println("Input accepted.");
4. Control Flow inside Loops (break and continue)
break: Immediately terminates the innermost loop or switch structure.continue: Skips the rest of the current iteration and jumps to the next iteration.