4.1

while Loops

AP Computer Science A

Syntax

java
while (condition) {
    // body — executes repeatedly
}

Basic examples

Counting up

java
int count = 1;
while (count <= 5) {
    System.out.println(count);
    count++;
}
// Output: 1 2 3 4 5

Counting down

java
int n = 5;
while (n > 0) {
    System.out.print(n + " ");
    n--;
}
System.out.println("Go!");
// Output: 5 4 3 2 1 Go!

The loop body must make progress

java
// INFINITE LOOP — count never changes!
int count = 1;
while (count <= 5) {
    System.out.println(count);
    // forgot count++; → prints 1 forever
}

// INFINITE LOOP — wrong direction!
int x = 10;
while (x > 0) {
    x++;  // should be x-- → x grows forever
}

Loop patterns

Accumulator — summing values

java
int sum = 0;
int n = 1;
while (n <= 100) {
    sum += n;   // add current number to sum
    n++;
}
System.out.println(sum);   // 5050

Counter — counting matches

java
String text = "Hello, World!";
int spaces = 0;
int i = 0;
while (i < text.length()) {
    if (text.substring(i, i + 1).equals(" ")) {
        spaces++;
    }
    i++;
}
System.out.println("Spaces: " + spaces);   // 1

Sentinel — loop until a special value

java
// Process numbers until user enters -1
int input = 0;
int total = 0;
while (input != -1) {
    total += input;
    // input = scanner.nextInt(); // get next number
}

Finding digits

java
// Count the digits in a number
int num = 12345;
int digits = 0;
while (num > 0) {
    digits++;
    num /= 10;   // remove last digit
}
System.out.println(digits);  // 5

Off-by-one errors

java
// Prints 1-5 (5 times)
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

// Prints 1-4 (4 times) — off by one!
int i = 1;
while (i < 5) {
    System.out.println(i);
    i++;
}

// Prints 0-4 (5 times)
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

while loop with Strings

java
// Reverse a string
String original = "Java";
String reversed = "";
int index = original.length() - 1;

while (index >= 0) {
    reversed += original.substring(index, index + 1);
    index--;
}
System.out.println(reversed);  // "avaJ"

Zero-iteration loop

java
int x = 10;
while (x < 5) {
    System.out.println(x);   // never runs
    x++;
}
// Nothing is printed

AP Exam Tips

Common Mistakes

Key Vocabulary