Fiveable
Fiveable
AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

4.1 While Loops

Verified for the 2025 AP Computer Science A examCitation:

Iteration is a fundamental programming concept that allows us to execute a block of code repeatedly. Rather than writing the same code multiple times, loops give us the power to repeat actions until a certain condition is met. The while loop is one of Java's primary iteration structures, enabling programs to process data repeatedly, gather input, or perform calculations until specific criteria are satisfied. This guide explores how while loops work, their common applications, and how to use them effectively in your Java programs.

Understanding while Loops

A while loop repeatedly executes a block of code as long as a specified Boolean statement (condition) evaluates to true. Once the condition becomes false, the loop stops, and program execution continues with the code following the loop.

Basic Syntax

Components of a while loop:

  • The while keyword
  • A condition in parentheses that evaluates to a boolean value
  • The loop body enclosed in curly braces containing the code to be repeated
while (condition) {
    // Loop body - code to be repeated

}

How while Loops Work

  1. The condition is evaluated before each iteration
  2. If the condition is true, the loop body executes
  3. After executing the loop body, control returns to step 1
  4. If the condition is false, the loop terminates, and execution continues with the statement after the loop (Counter: a variable that keeps track of a value, usually used to count or iterate through a loop.)
int count = 1;
while (count <= 5) {
    System.out.println("Count is: " + count);
    count++; // Increment the counter
}
System.out.println("Loop finished!");

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Loop finished!

Common Loop Patterns

Counter-Controlled Loops

A counter is a variable that keeps track of the number of iterations. This pattern is used when you need to perform an action a specific number of times:

int counter = 0;
while (counter < 10) {
    System.out.println("Iteration: " + counter);
    counter++;
}

Sentinel-Controlled Loops

A sentinel-controlled loop continues until it encounters a specific value (the sentinel):

import java.util.Scanner;

public class SentinelExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter numbers to sum (enter -1 to stop):");
        
        int sum = 0;
        int input = scanner.nextInt();
        
        while (input != -1) {
            sum += input;
            input = scanner.nextInt();
        }
        
        System.out.println("Sum: " + sum);
        scanner.close();
    }
}

Flag-Controlled Loops

A flag is a boolean variable that controls loop execution:

boolean found = false;  // Flag initialization
int[] numbers = {5, 10, 15, 20, 25};
int target = 15;
int i = 0;

while (i < numbers.length && !found) {
    if (numbers[i] == target) {
        found = true;  // Set flag to true when target is found
        System.out.println("Found " + target + " at position " + i);
    }
    i++;
}

if (!found) {
    System.out.println(target + " not found in the array.");
}

Infinite Loops

An infinite loop occurs when the loop condition never becomes false. This is sometimes intentional but often a logical error:

  • Break statement: used in loops (such as for and while loops) and switch statements to terminate their execution prematurely. It allows programmers to exit out of these constructs before reaching their natural end.
// Intentional infinite loop
while (true) {
    System.out.println("This will print forever unless interrupted");
    // Usually needs a break statement or other mechanism to exit
}
// Accidental infinite loop
int counter = 1;
while (counter > 0) {
    System.out.println("Current count: " + counter);
    counter++; // counter will never be <= 0, so the loop never ends
}

To avoid accidental infinite loops:

  • Ensure your loop condition will eventually become false
  • Make sure variables in the condition are updated in the loop body
  • Consider using a break statement for exceptional cases

Controlling Loop Execution

The break Statement

A break statement immediately exits a loop, skipping any remaining iterations:

int i = 1;
while (i <= 10) {
    System.out.println(i);
    if (i == 5) {
        System.out.println("Breaking the loop at 5");
        break; // Exit the loop when i equals 5
    }
    i++;
}

The return Statement

A return statement inside a loop not only exits the loop but also exits the entire method:

public boolean containsValue(int[] array, int value) {
    int i = 0;
    while (i < array.length) {
        if (array[i] == value) {
            return true; // Immediately exits the method with true
        }
        i++;
    }
    return false; // Only reached if the value is not found
}

Input Validation with while Loops

The following example incorporates exception handling to catch invalid inputs. The try-catch block handles the NumberFormatException that occurs if the user enters something that can't be parsed into an integer.

The Scanner class combined with while loops is perfect for validating user input:

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age = -1;
        
        while (age < 0 || age > 120) {
            System.out.print("Enter your age (0-120): ");
            try {
                age = Integer.parseInt(scanner.nextLine());
                if (age < 0 || age > 120) {
                    System.out.println("Age must be between 0 and 120.");
                }
            } catch (NumberFormatException e) {
                System.out.println("Please enter a valid number.");
            }
        }
        
        System.out.println("Your age is: " + age);
        scanner.close();
    }
}

Common Applications of while Loops

Computing Sums or Products

int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("Sum of numbers 1 to 100: " + sum);

Testing for Divisibility

Using the divisibility modulo operator (%):

// Find the first 5 numbers divisible by both 4 and 7
int count = 0;
int num = 1;

while (count < 5) {
    if (num % 4 == 0 && num % 7 == 0) {
        System.out.println(num + " is divisible by both 4 and 7");
        count++;
    }
    num++;
}

Reading File Data

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReading {
    public static void main(String[] args) {
        try {
            File file = new File("data.txt");
            Scanner fileScanner = new Scanner(file);
            
            while (fileScanner.hasNextLine()) {
                String data = fileScanner.nextLine();
                System.out.println(data);
            }
            
            fileScanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}

Ensuring Loop Termination

Using finally blocks

A finally block in combination with exception handling can ensure resources are properly closed regardless of how the loop exits:

Scanner scanner = new Scanner(System.in);
try {
    boolean validInput = false;
    while (!validInput) {
        try {
            System.out.print("Enter a positive number: ");
            int number = Integer.parseInt(scanner.nextLine());
            if (number > 0) {
                System.out.println("You entered: " + number);
                validInput = true;
            } else {
                System.out.println("Number must be positive.");
            }
        } catch (NumberFormatException e) {
            System.out.println("That's not a valid number. Try again.");
        }
    }
} finally {
    scanner.close(); // This will always execute, ensuring the scanner is closed
}

Comparing while Loops and for Loops

While Java provides several types of loops, including the for loop, the while loop is particularly well-suited for certain scenarios:

Loop TypeBest Used When
while loopNumber of iterations is unknown beforehand
for loopNumber of iterations is known or when iterating through collections
// while loop for unknown number of iterations
int sum = 0;
int num = scanner.nextInt();
while (num != -1) {
    sum += num;
    num = scanner.nextInt();
}

// for loop for known number of iterations
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}

Common Mistakes with while Loops

  1. Forgetting to update the loop control variable

    int i = 0;
    while (i < 10) {
        System.out.println(i);
        // Missing i++; creates an infinite loop
    }
    
  2. Incorrect condition logic

    // Intended to loop while i is less than 10
    int i = 0;
    while (i > 10) { // Should be i < 10
        // This loop body will never execute
        i++;
    }
    
  3. Off-by-one errors

    int i = 1;
    while (i < 10) { // Loops from 1 to 9, not 1 to 10
        i++;
    }
    
    // To loop from 1 to 10:
    int i = 1;
    while (i <= 10) {
        i++;
    }
    

Key Takeaways

  • A while loop repeatedly executes code as long as its condition is true
  • The loop condition is evaluated before each iteration
  • Use counter, sentinel, or flag variables to control loop execution
  • Be careful to avoid infinite loops by ensuring the condition will eventually become false
  • Break and return statements provide ways to exit a loop early
  • While loops are ideal when the number of iterations is not known in advance

While loops are an essential tool for handling repetitive tasks and creating dynamic, responsive programs. By understanding their behavior and common patterns, you can use them effectively to solve a wide range of programming problems. In the next section, we'll explore for loops, which provide a more compact syntax for iteration when the number of repetitions is known beforehand.

Key Terms to Review (14)

Boolean Statement: A boolean statement is an expression that evaluates to either true or false. It is used in programming to make decisions and control the flow of a program.
Break statement: The break statement is used in loops (such as for and while loops) and switch statements to terminate their execution prematurely. It allows programmers to exit out of these constructs before reaching their natural end.
Counter: A counter is a variable that keeps track of a value, usually used to count or iterate through a loop.
Divisibility modulo: Divisibility modulo refers to determining whether one number is divisible by another using modular arithmetic. It involves calculating the remainder when dividing one number by another.
Exception Handling: Exception handling is a mechanism in programming that allows you to handle and manage errors or exceptional situations that may occur during the execution of a program. It helps prevent the program from crashing by providing alternative paths or actions when an error occurs.
Finally block: A finally block is a section of code that follows a try-catch block and is always executed, regardless of whether an exception occurs or not. It is commonly used to perform cleanup tasks or release resources.
For Loop: A for loop is a control flow statement that allows you to repeatedly execute a block of code for a specified number of times or until certain conditions are met.
Flag: In programming, a flag is a variable or condition that acts as a signal or indicator. It helps control the flow of execution within a program.
Infinite Loop: An infinite loop is a programming construct where a set of instructions keeps repeating indefinitely, causing the program to get stuck and not progress further.
Iteration: Iteration refers to the process of repeating a set of instructions multiple times in order to achieve a desired outcome. It allows for efficient execution of repetitive tasks without having to write redundant code.
Loop Body: The loop body refers to the block of code that gets executed repeatedly in a loop. It contains the instructions that are repeated until the loop condition becomes false.
NumberFormatException: NumberFormatException is an exception that occurs when you try to convert a string into a numeric type (like int or double), but the string does not have the appropriate format for conversion.
Return Statement: A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.
Scanner class: The Scanner class is a built-in Java class that allows users to read input from various sources, such as the keyboard or a file.