Lesson 2.7: while Loops

Unit 2 · Lesson 2.7 · Code Mechanics

Lesson 2.7: while Loops

🕑 30–35 min · 8 Practice Questions · 4 Mastery Questions · Trace + Output Predictor + Count

What You'll Learn

  • 2.7.A: Identify when an iterative process is required.
  • Write while loops with correct initialization, condition, and update.
  • Trace while loop 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.
Tier 2 · AP Practice

Practice Questions

MCQ 1
What is printed?

int n = 3;
while (n > 0) {
    System.out.print(n + " ");
    n--;
}
A 3 2 1 0
B 3 2 1
C 2 1 0
D Nothing is printed
B. n starts at 3. Loop body runs for n=3,2,1 (condition 3>0, 2>0, 1>0 all true). When n becomes 0, condition 0>0 is false and loop exits. Output: 3 2 1.
MCQ 2
How many times does the loop body execute?

int count = 0;
while (count < 5) {
    count += 2;
}
A 2
B 3
C 5
D Infinite
B. count goes 0, 2, 4, then 6. At 6: 6<5 is false. Body ran for count=0,2,4 — 3 times.
MCQ 3
What is the value of total after this code?

int total = 0;
int i = 1;
while (i <= 4) {
    total += i;
    i++;
}
A 4
B 10
C 16
D 0
B. total accumulates 1+2+3+4 = 10. The loop runs for i=1,2,3,4. At i=5, condition fails.
MCQ 4
Which code segment produces an infinite loop?
Predict the answer before reading the options.
A
int x = 10;
while (x > 0) {
    x--;
}
B
int x = 1;
while (x != 10) {
    x += 3;
}
C
int x = 1;
while (x < 10) {
    x++;
}
D
int x = 0;
while (x < 10) {
    System.out.println(x);
}
D. x is never updated inside the body, so x stays 0 and 0<10 is always true. B also runs forever (x jumps 1,4,7,10 — wait, it hits 10 so not infinite). D is the only infinite loop.
MCQ 5
What is printed?

int k = 6;
while (k > 0) {
    System.out.print(k + " ");
    k -= 2;
}
A 6 4 2 0
B 6 4 2
C 4 2
D Nothing
B. k goes 6,4,2 (all >0, loop runs). At k=0: 0>0 is false, loop ends. Output: 6 4 2. Zero is not printed because the condition fails before the body runs.
MCQ 6
A student wants to print numbers 1 through 10. Which has an off-by-one error?
Predict the answer before reading the options.
A
int i=1;
while(i<=10){System.out.println(i);i++;}
B
int i=1;
while(i<10){System.out.println(i);i++;}
C
int i=0;
while(i<10){i++;System.out.println(i);}
D
int i=1;
while(i!=11){System.out.println(i);i++;}
B. 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.
MCQ 7
What is printed?

int n = 15;
while (n > 0) {
    if (n % 3 == 0) {
        System.out.print(n + " ");
    }
    n -= 3;
}
A 15 12 9 6 3
B 15 12 9 6 3 0
C 12 9 6 3
D 15 9 3
A. n starts at 15, decrements by 3. Values: 15,12,9,6,3. All are divisible by 3 (15%3=0, etc.). At n=0: 0>0 is false, loop ends. Output: 15 12 9 6 3.
MCQ 8
Which BEST describes the condition under which a while loop body executes zero times?
Predict the answer before reading the options.
A When the loop variable is not initialized
B When the boolean expression is false before the first iteration
C When the loop body has no statements
D When the boolean expression is always true
B. The while condition is evaluated before every iteration, including the first. If it is false initially, the body never runs. (EK 2.7.A.3)
PRACTICE WITH A GAME — CHOOSE ONE:
Trace the Variable — while Loops
Trace this while loop and enter the final value of the variable.
Question 1 of 3  ·  Score: 0

After the code runs, what is the value of ?

Done!
You got 0 of 3 correct.
Output Predictor — while Loops
Trace the while loop and type the exact output.
Question 1 of 3  ·  Score: 0

Done!
You got 0 of 3 correct.
Predict the Count — while Loops
Count how many times the loop body executes.
Question 1 of 3  ·  Score: 0

How many times does the loop body execute?

Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: while Loops

MCQ 1
What is printed?

int a = 1;
int b = 1;
while (a <= 20) {
    int temp = b;
    b = a + b;
    a = temp;
    System.out.print(a + " ");
}
Predict the answer before reading the options.
A 1 2 3 5 8 13
B 1 1 2 3 5 8 13
C 1 2 3 5 8 13 21
D 2 3 5 8 13 21
A. Fibonacci: a=1,b=1. temp=1,b=2,a=1→print 1. temp=2,b=3,a=2→print 2. temp=3,b=5,a=3→print 3. temp=5,b=8,a=5→print 5. temp=8,b=13,a=8→print 8. temp=13,b=21,a=13→print 13. temp=21,b=34,a=21: 21>20, loop ends. Output: 1 2 3 5 8 13.
MCQ 2
Which condition creates an infinite loop?

int x = 5;
while (/* condition */) {
    x -= 2;
}
Predict the answer before reading the options.
A x > 0
B x != 0
C x >= 0
D x > -100
B. x goes 5,3,1,-1,-3,... It skips 0 (decrements by 2 from odd number). Condition x!=0 is always true for odd starting value, creating an infinite loop. A,C,D all eventually become false.
MCQ 3
What is the value of result?

int result = 1;
int n = 5;
while (n > 1) {
    result *= n;
    n--;
}
A 5
B 15
C 120
D 24
C. Factorial: result = 5×4×3×2 = 120. When n=1: condition 1>1 is false, loop ends. result = 120.
MCQ 4
I. A while loop always executes at least once.  II. A while loop may execute zero times.  III. The condition is checked after the body in a while loop.

Which are TRUE?
Predict the answer before reading the options.
A I only
B II only
C I and III only
D I, II, and III
B. II is true: if initial condition is false, body never runs. (EK 2.7.A.3) I is false. III is false: condition is checked BEFORE the body. (EK 2.7.B.1)

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.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]