Module: Control Flow in Java

Loops (for, while, do-while)

Java Core: Control Flow - Loops (for, while, do-while)

Loops are fundamental control flow statements that allow you to repeatedly execute a block of code. Java provides three main types of loops: for, while, and do-while. Each loop is suited for different scenarios.

1. for Loop

The for loop is typically used when you know in advance how many times you want to execute a block of code.

Syntax:

for (initialization; condition; increment/decrement) {
  // Code to be executed repeatedly
}
  • Initialization: Executed only once at the beginning of the loop. Typically used to declare and initialize a loop counter variable.
  • Condition: Evaluated before each iteration. If the condition is true, the loop body is executed. If false, the loop terminates.
  • Increment/Decrement: Executed after each iteration. Typically used to update the loop counter variable.

Example:

// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
  System.out.println(i);
}

Explanation:

  1. int i = 1;: Initializes the loop counter i to 1.
  2. i <= 5;: Checks if i is less than or equal to 5. If true, the loop body executes.
  3. System.out.println(i);: Prints the current value of i.
  4. i++;: Increments i by 1.
  5. Steps 2-4 repeat until i becomes 6, at which point the condition i <= 5 becomes false, and the loop terminates.

Variations:

  • Multiple Initialization/Increment/Decrement: You can have multiple statements separated by commas in the initialization and increment/decrement sections.

    for (int i = 0, j = 10; i < 5; i++, j--) {
      System.out.println("i: " + i + ", j: " + j);
    }
    
  • Empty Loop Body: The loop body can be empty if all the logic is contained within the initialization, condition, and increment/decrement sections.

    int sum = 0;
    for (int i = 1; i <= 10; sum += i, i++); // Calculate sum of 1 to 10
    System.out.println("Sum: " + sum);
    
  • Infinite Loop: If the condition is always true, the loop will run indefinitely. Be careful to avoid this!

    // Avoid this!
    // for (;;) {
    //   System.out.println("This will print forever!");
    // }
    

2. while Loop

The while loop is used when you want to execute a block of code repeatedly as long as a condition is true. The number of iterations is not necessarily known in advance.

Syntax:

while (condition) {
  // Code to be executed repeatedly
}
  • Condition: Evaluated before each iteration. If the condition is true, the loop body is executed. If false, the loop terminates.

Example:

// Print numbers from 1 to 5 using a while loop
int i = 1;
while (i <= 5) {
  System.out.println(i);
  i++;
}

Explanation:

  1. int i = 1;: Initializes the loop counter i to 1.
  2. while (i <= 5): Checks if i is less than or equal to 5. If true, the loop body executes.
  3. System.out.println(i);: Prints the current value of i.
  4. i++;: Increments i by 1.
  5. Steps 2-4 repeat until i becomes 6, at which point the condition i <= 5 becomes false, and the loop terminates.

Important: Make sure the condition eventually becomes false to avoid an infinite loop. The loop body must contain code that modifies the variables involved in the condition.

3. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once, even if the condition is initially false.

Syntax:

do {
  // Code to be executed repeatedly
} while (condition);
  • Condition: Evaluated after each iteration. If the condition is true, the loop body is executed again. If false, the loop terminates.

Example:

// Print "Hello" at least once, then continue as long as a condition is true
int count = 0;
do {
  System.out.println("Hello");
  count++;
} while (count < 3);

Explanation:

  1. System.out.println("Hello");: Prints "Hello". This line is executed at least once.
  2. count++;: Increments count by 1.
  3. while (count < 3): Checks if count is less than 3. If true, the loop body executes again.
  4. Steps 1-3 repeat until count becomes 3, at which point the condition count < 3 becomes false, and the loop terminates.

Key Difference between while and do-while:

  • while: Checks the condition before executing the loop body.
  • do-while: Checks the condition after executing the loop body.

Loop Control Statements

Java provides statements to control the execution of loops:

  • break: Terminates the loop immediately, regardless of the condition.
  • continue: Skips the rest of the current iteration and proceeds to the next iteration.

Example (using break):

for (int i = 1; i <= 10; i++) {
  if (i == 5) {
    break; // Exit the loop when i is 5
  }
  System.out.println(i);
}
// Output: 1 2 3 4

Example (using continue):

for (int i = 1; i <= 10; i++) {
  if (i % 2 == 0) {
    continue; // Skip even numbers
  }
  System.out.println(i);
}
// Output: 1 3 5 7 9

Choosing the Right Loop

  • for loop: Use when you know the number of iterations in advance.
  • while loop: Use when you want to repeat a block of code as long as a condition is true, and the number of iterations is not known beforehand.
  • do-while loop: Use when you want to execute a block of code at least once, and then continue as long as a condition is true.

Understanding these loop types and control statements is crucial for writing efficient and effective Java programs. Remember to always consider the possibility of infinite loops and ensure that your loop conditions eventually become false.