2.07 while Loops
Repeat code while a condition is true, trace loop control variables, and avoid infinite and off by one loops.
- 1. LxD Cycle Process
- 2. Lesson Plan
- 3. Reference Guide
- 4. Code Examples
- A. Simple: while Loops in Code
- Code Runner Challenge
- 5. Hacks & Practice Tasks
- 6. Grading Plan (1 Point Total)
- 7. Lesson Revisions & Feedback Evidence
- 8. Summary
- 9. References
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
whileloop repeats its body as long as the condition istrue. - The condition is checked before every pass. If it is
falsethe 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
whilewhen 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
breakandcontinue. 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);
5. Hacks & Practice Tasks
Prepare your submission IPYNB
- Create a new notebook in your portfolio homework area:
_notebooks/homework. - 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
---
- Add code cells for the Popcorn Hack and the Homework Hack. Ensure all code runs and output is visible.
- 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.
Activity 2: How Many Times?
Predict how many times the body runs, then let the counter run.
Activity 3: Infinite or Off by One?
What happens when this runs?
How many numbers does this print?
What is printed after this loop?
Activity 4: Assemble the Loop
Arrange the lines into a loop that adds 1 through 5 and prints Sum: 15.
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);
Homework Hack
Two short tasks.
- Finish the runner: keep doubling
amountuntil it is at leastgoal, counting how many doublings it took. - 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);
How many times does the body of this loop run?
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
amountuntil it reachesgoaland 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.
- 0.5 Doubling loop: The loop doubles
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: 1600andDoublings: 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
forloop, 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
Need to update a submission later? Open the submissions dashboard.