1. LxD Cycle Process

Empathize: Students write loops that never end because the update is missing, and loops that run one pass too many because of the wrong comparison. Both compile, so the only evidence is behaviour.

Define:

  • POV: CSA students need to see the condition being checked before every pass, because the check they cannot see is the one that ends the loop.
  • Learning Goal: Students will trace a loop pass by pass, count iterations, diagnose infinite and off by one loops, and assemble a correct loop from shuffled lines.

Ideate:

  • HMW Question: How might we make the condition check visible on every pass, including the final failing check that ends the loop?
  • Activity: A pass by pass tracer that shows the check, an iteration counter, a loop bug diagnosis, and an assemble-the-loop ordering task.

Prototype & Test: Activity 1 lets the bound drop to zero so the zero-pass case is something students observe rather than something they are told.


2. 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 (5 minutes)

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.

3. 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.

4. 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 ...

5. Hacks & Practice Tasks

Prepare your submission IPYNB

  1. Create a new notebook in your portfolio homework area: _notebooks/homework.
  2. Add one markdown cell at the top with the frontmatter:
---
layout: post
title: CSA Unit 2.07 while Loops HW
categories: [Java, While-Loops]
lesson_language: Java
lesson_topic: While-Loops HW
lesson_source: APCSA
lesson_type: lesson
permalink: /csa/unit_02/2_7_hw
author: yourGithubID
---
  1. Add code cells for the Popcorn Hack and the Homework Hack. Ensure all code runs and output is visible.
  2. Include a markdown cell before each code section explaining the concept.

Submission Safety Rules (Read First)

[IMPORTANT] To avoid grading errors, follow these rules exactly:

  • Write your prediction before you run each code section
  • Execute every code cell and leave the output visible
  • Show your work for any hand-traced prediction
  • Do not just copy code; explain what each line does
  • Label each question clearly

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 (In-Class)

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;
}

6. Grading Plan (1 Point Total)

Classroom Rubric

  • 0.2 points: Popcorn completion Student wrote a countdown that prints each number down to 1 and then Liftoff!, ending because the condition became false.

  • 0.8 points: Homework completion

    • 0.5 Doubling loop: The loop doubles amount until it reaches goal and counts the doublings, printing 1600 and 4.
    • 0.2 Quick check: The iteration count question is answered with the values of the control variable listed.
    • 0.1 Notebook quality: Every code cell executed with output visible, and a markdown cell before each code section explaining the concept.

Quick Validation Checklist

  • Present: initialise, test and update all present and in the right place
  • Present: countdown ends because of its condition, not a break
  • Absent: an update placed outside the loop body
  • Test: output reads Amount: 1600 and Doublings: 4

7. Lesson Revisions & Feedback Evidence

Feedback Received: Team review of the Unit 2 set found that these lessons did not follow the section format used by the Unit 1 lessons, and that they ended without the assignment submission form every other CSA lesson provides.

Revision Made: The lesson was reorganised into the shared CSA lesson format, so it now opens with the LxD cycle and lesson plan, states its reference material before the code, and groups the activities, Popcorn Hack and Homework Hack under one practice section. The duplicate lesson heading was removed, and the page now renders the standard Submit Assignment form at the end.

Design Decision Kept: Activity 1 lets the bound drop to zero so the zero-pass case is something students observe rather than something they are told.

Open Item: Record peer feedback from the team teach delivery here once the lesson has been taught.


8. Summary

  • while (condition) { body } checks first, then runs, then checks again.
  • Initialize before, test in the condition, update inside.
  • No update means an infinite loop; the wrong comparison means an off by one error.
  • The body can run zero times.
  • Next lesson: the for loop, which packs initialize, test, and update into one line.

9. References

College Board Course and Exam Description

Topic 2.7, while Loops, is required content on the AP Computer Science A Exam. The objective quoted in section 2 of this lesson 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

Submit Assignment

Click to upload or drag and drop
PDF, ZIP, images, documents, or Jupyter notebooks (.ipynb) (Max 10MB per file)

Need to update a submission later? Open the submissions dashboard.