Reference Guide

Key Ideas

  • A while loop repeats its body as long as the condition is true.
  • The condition is checked before every pass. If it is false the first time, the body runs zero times.
  • A loop control variable needs three things: initialize it before the loop, test it in the condition, update it inside the body.
  • Infinite loop: the condition never becomes false, usually because the update is missing.
  • Off by one error: the loop runs one time too many or too few. Check < versus <= carefully.
  • Use while when you do not know in advance how many times to repeat.

Shape of the Loop

int i = 1;              // 1. initialize
while (i <= 5) {        // 2. test before each pass
    System.out.println(i);
    i++;                // 3. update, or the loop never ends
}
  • Java also has break and continue. The AP exam does not test them, so write loops that end because the condition becomes false.

College Board Requirements

AP CSA Unit 2, Topic 2.7: while Loops.

This lesson is built directly against the College Board’s stated learning objective for this topic:

Represent iterative processes using a while loop.

Topic 2.7, while Loops, is required content on the AP Computer Science A Exam. The learning objective quoted above is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.


Lesson Plan

Learning Objective: Represent iterative processes using a while loop.

Success Criteria: You can trace a while loop pass by pass, name the three jobs of a loop control variable, and tell an infinite loop apart from an off by one error.

Tech Talk & Introduction

A while loop repeats its body as long as its condition stays true. The condition is checked before every pass, including the first.

  • A loop control variable needs three things: initialise before the loop, test in the condition, update inside the body.
  • Leave out the update and the condition never changes, which is an infinite loop.
  • Choose < or <= carefully. The wrong one runs the body one time too many or too few.
  • If the condition is false the first time, the body runs zero times.

Code Examples

A. Simple: while Loops in Code

A pyramid built with three while loops: one for rows, one for spaces, one for stars. Run it, then change height.

Code Runner Challenge

Pyramid pattern with while loops. Change height and run again.

View IPYNB Source
// CODE_RUNNER: Pyramid pattern with while loops. Change height and run again.
public class PyramidPattern {
    public static void main(String[] args) {
        int height = 5;   // try 3 and 8
        int row = 1;

        while (row <= height) {
            int spaces = height - row;
            int stars = 2 * row - 1;

            int spaceCount = spaces;
            while (spaceCount > 0) {
                System.out.print(" ");
                spaceCount--;
            }

            int starCount = stars;
            while (starCount > 0) {
                System.out.print("*");
                starCount--;
            }

            System.out.println();
            row++;
        }
    }
}
PyramidPattern.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks

Activity 1: Trace the Loop

Step through it now. Watch the condition get checked before every pass, including the final check that ends the loop. Set n to 0 to see the body run zero times.

Countdown Trace
Each yellow line is the statement Java is about to run.

Activity 2: How Many Times?

Predict how many times the body runs, then let the counter run.

Halving Loop
Type your prediction first. Then press Run and count.

Activity 3: Infinite or Off by One?

Loop Bugs
Each loop has a problem or a trick. Read the condition and the update carefully.
Question 1

What happens when this runs?

int count = 0;
while (count < 3) {
System.out.println("Hi");
}
Question 2

How many numbers does this print?

int k = 10;
while (k >= 0) {
System.out.println(k);
k = k - 2;
}
Question 3

What is printed after this loop?

int total = 0;
int n = 5;
while (n > 5) {
total += n;
n--;
}
System.out.println(total);

Activity 4: Assemble the Loop

Arrange the lines into a loop that adds 1 through 5 and prints Sum: 15.

Sum with a while Loop
Initialize, test, update. All three must be in the right place.
int sum = 0;
int i = 1;
while (i <= 5) {
sum = sum + i;
i++;
}
System.out.println("Sum: " + sum);

Popcorn Hack

Write a countdown. Starting from start, print each number down to 1, then print Liftoff!. The loop must end because of its condition.

Code Runner Challenge

Popcorn hack: countdown with a while loop. Expected: 5 4 3 2 1 then Liftoff!

View IPYNB Source
// CODE_RUNNER: Popcorn hack: countdown with a while loop. Expected: 5 4 3 2 1 then Liftoff!
public class Countdown {
    public static void main(String[] args) {
        int start = 5;

        // TODO: while loop that prints start, start - 1, ..., 1
        // TODO: then print "Liftoff!"
    }
}
Countdown.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack

Two short tasks.

  1. Finish the runner: keep doubling amount until it is at least goal, counting how many doublings it took.
  2. Answer the quick check.

Code Runner Challenge

Homework: double until the goal is reached. Expected output: Amount 1600, Doublings 4.

View IPYNB Source
// CODE_RUNNER: Homework: double until the goal is reached. Expected output: Amount 1600, Doublings 4.
public class Doubling {
    public static void main(String[] args) {
        int amount = 100;
        int goal = 1000;
        int doublings = 0;

        // TODO: while amount is less than goal, double it and add 1 to doublings

        System.out.println("Amount: " + amount);          // expected: 1600
        System.out.println("Doublings: " + doublings);    // expected: 4
    }
}
Doubling.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
Homework Quick Check
Type a number.

How many times does the body of this loop run?

int i = 0;
while (i < 10) {
i = i + 3;
}

References

College Board Course and Exam Description

Topic 2.7, while Loops, is required content on the AP Computer Science A Exam. The learning objective quoted in section 3 (College Board Requirements) is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.

Outside Academic Reference

The specification defines the while statement as evaluating its condition before each execution of the body, which is the rule that produces the zero-pass case the lesson demonstrates.

Reference List

College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/courses/ap-computer-science-a

Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java language specification: Java SE 21 edition. Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.12

All Java lessons