While Loops

beginner65 min

Why loops exist

Copy-pasting the same statements does not scale. A loop runs a block until a condition becomes false (or until you break).

Without a loop

With a while loop

Basic while loop

While Loop Syntax:

Infinite Loops

Using while (true) creates an infinite loop that runs forever unless explicitly stopped with a break statement. This is useful for user input scenarios.

Infinite Loop Examples:

// This runs forever (until break is encountered)
while (true) {
    System.out.println("I can program!");
}

// Practical infinite loop with break condition
int robotSpeed = 0;
while (true) {
    robotSpeed += 10;
    System.out.println("Robot speed: " + robotSpeed);
    
    if (robotSpeed >= 100) {
        System.out.println("Maximum speed reached!");
        break;  // Exit the loop
    }
}

User Input with While Loops:

While Loops with Conditions

Instead of using while (true) with break, you can put the condition directly in the while statement. This is more elegant when you know the exact condition to check.

Conditional While Loop:

Try It Yourself:

Exercise 1: While Loop Practice

  • Create a simple counting loop that prints numbers 1 to 10
  • Build a robot battery monitor using while(true) and break
  • Make a number guessing game with user input validation
  • Create a sensor reading loop that stops when target value is reached
Practice creating different types of while loops: