Java Learner logo

Module 3: Control Flow and Decision Making

Lesson focus

Iteration: For, While, and Do-While Loops

Learn how to repeat actions using Java's three main loop constructs: `for`, `while`, and `do-while`. Also covers the enhanced `for-each` loop and the `break` and `continue` statements.

Why Use Loops? Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly, saving you from writing the same code over and over again.

The for Loop: The for loop is ideal when you know exactly how many times you want to repeat the code. It consists of three parts, separated by semicolons:

  • Initialization: A statement that runs once before the loop starts (e.g., int i = 0).
  • Condition: A boolean expression that is checked before each iteration. If it's true, the loop continues; if false, the loop stops.
  • Update: A statement that runs at the end of each iteration (e.g., i++).

The while Loop: The while loop is best when you don't know the exact number of iterations, but you know the condition that needs to be met for the loop to stop. The condition is checked before each iteration.

The do-while Loop: This loop is similar to the while loop, but with one key difference: the condition is checked after the code block is executed. This guarantees that the loop body will run at least once.

The Enhanced for-each Loop: This is a simplified loop for iterating over all elements in an array or collection. It is less error-prone as you don't need to manage an index variable.

  • Syntax: for (Type element : collection) { ... }

Controlling Loops: break and continue

  • break: Immediately terminates the loop and continues execution at the statement following the loop.
  • continue: Skips the rest of the current iteration and proceeds to the next iteration of the loop.

Mini-Exercise: Write a program that uses a for loop to print the numbers from 1 to 10. Then, modify it to use a while loop to achieve the same result. Finally, use a for loop to find the sum of all even numbers between 1 and 100.

// For loop to print 0 to 4
for (int i = 0; i < 5; i++) {
    System.out.println("i = " + i);
}

// While loop to count down from 3
int countdown = 3;
while (countdown > 0) {
    System.out.println(countdown);
    countdown--;
}

// For-each loop for an array
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
    System.out.println("Hello, " + name);
}
// Using break and continue
for (int i = 0; i < 10; i++) {
    if (i == 3) {
        continue; // Skip printing 3
    }
    if (i == 7) {
        break; // Stop the loop at 7
    }
    System.out.print(i + " "); // Output: 0 1 2 4 5 6 
}

Lesson quiz

Which loop construct guarantees that its body will be executed at least one time?

Next lesson →