While Loops

Why Use Loops?

Loops allow programs to repeat code efficiently. Instead of writing the same code multiple times, loops execute a block of code repeatedly based on a condition.

Problem: Repetitive Code

// Without loops - inefficient and inflexible
Scanner scanner = new Scanner(System.in);
int sum = 0;

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

// What if we need 100 numbers? 1000 numbers?
System.out.println("The sum is " + sum);

Solution: Using While Loops

// With loops - efficient and flexible
Scanner scanner = new Scanner(System.in);
int numbersRead = 0;
int sum = 0;

while (true) {
    if (numbersRead == 5) {
        break;  // Exit when we've read 5 numbers
    }
    
    System.out.println("Input number");
    sum = sum + Integer.valueOf(scanner.nextLine());
    numbersRead = numbersRead + 1;
}

System.out.println("The sum of the numbers is " + sum);

Basic While Loop Structure:

while (condition) { // Code to repeat // This block executes while condition is true } // Simple counting example int count = 1; while (count <= 5) { System.out.println("Count: " + count); count = count + 1; // Important: update the condition! }

While Loop Syntax:

while (condition) {
    // Code to repeat
    // This block executes while condition is true
}

// Simple counting example
int count = 1;
while (count <= 5) {
    System.out.println("Count: " + count);
    count = count + 1;  // Important: update the condition!
}

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:

Scanner scanner = new Scanner(System.in);

// Keep asking until user wants to exit
while (true) {
    System.out.println("Exit? (y exits)");
    String input = scanner.nextLine();
    
    if (input.equals("y")) {
        break;  // Exit if user enters 'y'
    }
    
    System.out.println("Ok! Let's carry on!");
}

System.out.println("Ready!");

// Robot example: Read sensor values until threshold
while (true) {
    System.out.println("Input sensor reading (0 to quit)");
    int reading = Integer.valueOf(scanner.nextLine());
    
    if (reading == 0) {
        break;
    }
    
    System.out.println("Sensor value: " + reading);
}

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:

// Count from 1 to 5 using condition
int number = 1;

while (number < 6) {
    System.out.println(number);
    number++;  // Shorthand for number = number + 1
}

// Robot example: Drive until target reached
double distanceToTarget = 100.0;
double speed = 10.0;

while (distanceToTarget > 0) {
    System.out.println("Distance remaining: " + distanceToTarget + " cm");
    distanceToTarget -= speed;  // Move closer to target
    
    // Slow down as we approach
    if (distanceToTarget < 20) {
        speed = 5.0;
    }
}

System.out.println("Target reached!");

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:

Open full interactive app