Loop Control

beginner40 min

break

break leaves the loop immediately and continues on the line after the loop.

break example

Continue Statement

continue skips the rest of the current iteration and goes back to the condition check.

continue example

Loop Execution Timing

Important: Loop conditions are only checked at the beginning of each iteration and when the loop first starts. Changes to variables inside the loop don’t immediately stop the loop.

Loop Timing Example:

int number = 1;

while (number != 2) {
    System.out.println(number);  // prints 1
    number = 2;                  // Now number equals 2
    System.out.println(number);  // prints 2
    number = 1;                  // Back to 1 - loop continues!
}
// This loop runs forever!

// The condition (number != 2) is only checked:
// 1. When loop starts
// 2. After reaching the closing }

// For loop example:
for (int i = 0; i != 100; i++) {
    System.out.println(i);       // prints current i
    i = 100;                     // Set i to 100
    System.out.println(i);       // prints 100
    i = 0;                       // Reset i to 0
}  // At this point, i++ makes i = 1, loop continues
// This loop also runs forever!

Loop Control Best Practices:

Important Guidelines:

  • Always update loop variables: Ensure conditions can eventually become false
  • Use break wisely: Provide clear exit conditions for infinite loops
  • Continue for validation: Skip invalid input without exiting the loop
  • Single clear task: Each if-statement should have one specific purpose

Try It Yourself:

Exercise 1: Loop Control Practice

  • Create a number validator that uses continue for invalid input
  • Build a menu system that uses break to exit
  • Make a sensor monitoring system with both break and continue
  • Create a robot safety system with emergency break conditions
Practice using break and continue statements: