Lesson 2.7: while Loops
Lesson 2.7: while Loops
What You'll Learn
- 2.7.A: Identify when an iterative process is required.
- Write
whileloops with correct initialization, condition, and update. - Trace
whileloop execution step by step. - Identify infinite loops and off-by-one errors. (EK 2.7.A.2, 2.7.A.4)
- Explain when the loop body executes zero times. (EK 2.7.A.3)
Key Vocabulary
| Term | Definition |
|---|---|
| iteration statement | A control structure that changes sequential flow by repeating a segment of code zero or more times as long as a condition is true. (EK 2.7.A.1) |
| while loop | A type of iteration statement that evaluates the boolean condition before each iteration, including the first. Runs 0 or more times. (EK 2.7.B.1) |
| loop body | The block of statements enclosed in { } that executes each time the condition is true. |
| loop control variable | A variable whose value determines when the loop terminates. Must be initialized before the loop and updated inside the body. |
| infinite loop | A loop whose boolean expression never evaluates to false. The program runs forever (or until forcibly stopped). (EK 2.7.A.2) |
| off-by-one error | A bug where the loop iterates one too many or one too few times, usually from a wrong boundary condition (< vs <=). (EK 2.7.A.4) |
| sentinel value | A special value used as a stopping signal in a loop. When the loop variable reaches the sentinel, the loop terminates. |
How while Loops Work (EK 2.7.B.1)
A while loop repeats a block of statements as long as a boolean condition remains true. The condition is evaluated before each iteration, including the very first one. If the condition is false on the first check, the body never executes at all. This is the defining characteristic that distinguishes while from other potential loop types.
CED Connection (EK 2.7.A.1 & 2.7.B.1)
"Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true." and "In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first."
Syntax
while (booleanExpression) {
// body: executes each time condition is true
// MUST update the loop control variable here
}
// execution continues here when condition becomes false
Execution sequence — every iteration
| Step | What happens |
|---|---|
| 1. Evaluate condition | Compute the boolean expression. If false, skip to after the closing brace. |
| 2. Execute body | Run all statements inside { } from top to bottom. |
| 3. Update variable | The loop control variable must be updated in the body, or the condition never changes. |
| 4. Go back to step 1 | Re-evaluate the condition. Repeat until false. |
Worked Example — Full Trace (count from 1 to 5)
Trace each step explicitly:
int count = 1; // initialize before loop
while (count <= 5) { // check: 1<=5 true, 2<=5 true... 6<=5 false
System.out.print(count + " "); // prints: 1 2 3 4 5
count++; // update: prevents infinite loop
}
System.out.println("Done"); // always runs after loop
Output: 1 2 3 4 5 Done. The loop executes 5 times. On iteration 6, count is 6 and 6 <= 5 is false, so the body is skipped and execution continues after the loop.
The Loop Body Executes Zero Times (EK 2.7.A.3)
Because the condition is checked before the body runs, a while loop may execute its body zero times if the initial condition is already false. This is not an error — it is expected behavior for a pre-test loop. Code after the loop always runs regardless.
Worked Example — Zero Iterations
int n = 10;
while (n < 5) { // 10 < 5 = false immediately
System.out.println("Inside"); // NEVER executes
}
System.out.println("After"); // always runs → prints "After"
This is a key AP exam point: zero iterations is valid. The body is simply skipped. Code after the loop is never conditional.
Common Patterns
Worked Example — Countdown (decrement)
int n = 5;
while (n > 0) {
System.out.print(n + " ");
n--; // decrement toward stopping condition
}
// Output: 5 4 3 2 1
Worked Example — Sentinel Loop
// Loop until user enters -1
int value = getInput(); // first read before loop
while (value != -1) { // -1 is the sentinel
process(value);
value = getInput(); // read again inside body
}
// Terminates when sentinel is entered
The read-before-loop + read-at-end-of-body pattern is the standard sentinel loop. This ensures the sentinel itself is never processed.
Infinite Loops (EK 2.7.A.2)
An infinite loop occurs when the boolean expression never becomes false. This happens when the loop control variable is never updated, the update goes in the wrong direction, or the condition can never be reached. On the AP exam, infinite loop identification is a common spot-the-error question.
AP Trap: Forgetting to Update the Loop Variable
This loop never terminates because count never changes:
int count = 1;
while (count <= 5) {
System.out.println(count);
// forgot count++; → count stays 1 forever → infinite loop
}
AP Trap: Off-By-One Error (EK 2.7.A.4)
< vs <= changes whether the boundary value is included:
// Intended: print 1 through 10 (10 iterations)
int i = 1;
while (i < 10) { // BUG: stops at 9, prints 1-9 only (9 iterations)
System.out.print(i + " ");
i++;
}
// Fix: use <= to include the boundary
while (i <= 10) { /* ... */ } // prints 1-10 (10 iterations)
AP Trap: Modifying the Wrong Variable
Updating a different variable than the one in the condition causes an infinite loop:
int count = 0;
int total = 0;
while (count < 5) {
total++; // updates total, NOT count
// count never changes → infinite loop
}
Real-World Connection
Every waiting mechanism in software is a while loop. A server waits for client requests while the server is running. A game loop runs while the game is not over. A download manager retries while the connection fails. A spell checker scans while characters remain in the document. The while loop is the foundational tool for any algorithm that must repeat until a condition changes — which is most real-world algorithms.
Summary
- Condition checked before each iteration, including the first. (EK 2.7.B.1)
- Zero iterations is valid when the initial condition is false. (EK 2.7.A.3)
- Infinite loop occurs when the condition never becomes false. (EK 2.7.A.2)
-
Off-by-one error:
<vs<=determines whether the boundary value is included. (EK 2.7.A.4) - Three requirements: initialize the loop variable before the loop, test it in the condition, update it in the body.
- Sentinel pattern: read before the loop, test against the sentinel, re-read at end of body.
Practice Questions
int n = 3;
while (n > 0) {
System.out.print(n + " ");
n--;
}
3 2 1 0
3 2 1
2 1 0
3 2 1.int count = 0;
while (count < 5) {
count += 2;
}
total after this code?int total = 0;
int i = 1;
while (i <= 4) {
total += i;
i++;
}
int x = 10;
while (x > 0) {
x--;
}
int x = 1;
while (x != 10) {
x += 3;
}
int x = 1;
while (x < 10) {
x++;
}
int x = 0;
while (x < 10) {
System.out.println(x);
}
int k = 6;
while (k > 0) {
System.out.print(k + " ");
k -= 2;
}
6 4 2 0
6 4 2
4 2
6 4 2. Zero is not printed because the condition fails before the body runs.int i=1;
while(i<=10){System.out.println(i);i++;}
int i=1;
while(i<10){System.out.println(i);i++;}
int i=0;
while(i<10){i++;System.out.println(i);}
int i=1;
while(i!=11){System.out.println(i);i++;}
i < 10 stops at 9, missing 10. A correctly uses i<=10. C increments before printing so outputs 1-10. D stops when i reaches 11, correctly printing 1-10.int n = 15;
while (n > 0) {
if (n % 3 == 0) {
System.out.print(n + " ");
}
n -= 3;
}
15 12 9 6 3
15 12 9 6 3 0
12 9 6 3
15 9 3
15 12 9 6 3.After the code runs, what is the value of ?
How many times does the loop body execute?
Mastery: while Loops
int a = 1;
int b = 1;
while (a <= 20) {
int temp = b;
b = a + b;
a = temp;
System.out.print(a + " ");
}
1 2 3 5 8 13
1 1 2 3 5 8 13
1 2 3 5 8 13 21
2 3 5 8 13 21
int x = 5;
while (/* condition */) {
x -= 2;
}
x > 0
x != 0
x >= 0
x > -100
result?int result = 1;
int n = 5;
while (n > 1) {
result *= n;
n--;
}
Which are TRUE?
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]