01 / 20

while Loops

Master indefinite iteration in Java: learn how while loops repeat code as long as a Boolean condition remains true.

AP Computer Science A

What Is a Loop?

A loop is a control structure that repeats a block of code multiple times. Instead of writing the same statement over and over, a loop automates the repetition for you.

Without Loops
You write 100 print statements to print numbers 1 to 100.
With Loops
You write 3 lines: a condition, a body, and an update. Done.

Anatomy of a while Loop

while (condition) { // body: code to repeat // update: change something so // condition eventually becomes false }
Condition
A Boolean expression checked before each iteration.
Body
Statements that execute each time the condition is true.
Update
Part of the body that changes the loop variable to avoid infinite loops.

Execution Flow

Start condition == true? true Execute body loop back false Continue

Formal Syntax in Java

int count = 1; while (count <= 5) { System.out.println(count); count++; // update step }

while vs for

while loop for loop
Init location Before the loop Inside the header
Condition In the parentheses In the header (middle)
Update Inside the body In the header (end)
Best for Unknown iterations Known iterations
Risk Easier to forget update Update always visible

Step-by-Step Approach

1
Identify the loop variable. What value controls when the loop stops?
2
Initialize it before the loop. Set the starting value (e.g., int i = 0).
3
Write the condition. Express when the loop should continue, not when it should stop.
4
Write the body. Include the useful work and the update step that changes the loop variable.
5
Trace it. Mentally run through the first 2-3 iterations and the final iteration to verify correctness.

Example 1: Sum of Integers

Calculate the sum \(1 + 2 + 3 + \dots + n\) using a while loop.

int n = 10; int sum = 0; int i = 1; while (i <= n) { sum += i; i++; } System.out.println(sum); // 55

Example 2: Sentinel Value Loop

Read user input until a sentinel value of -1 is entered. This is a classic use case where the number of iterations is unknown.

Scanner sc = new Scanner(System.in); int num = sc.nextInt(); while (num != -1) { System.out.println("Got: " + num); num = sc.nextInt(); // read next } System.out.println("Done.");

Example 3: String Processing

Count the number of vowels in a String using a while loop with .charAt().

String word = "algorithm"; int idx = 0; int vowels = 0; while (idx < word.length()) { char ch = word.charAt(idx); if ("aeiou".indexOf(ch) != -1) { vowels++; } idx++; } // vowels == 3 (a, o, i)

Tracing a Loop

int x = 1; while (x < 16) { x *= 2; } System.out.println(x);
Iteration x (before) x (after x *= 2) \(x < 16\)?
112true
224true
348true
4816false

The Dreaded Infinite Loop

An infinite loop occurs when the condition never becomes false. The program freezes or runs forever.

int x = 5; while (x > 0) { System.out.println(x); // Oops! Forgot x--; }

Off-by-One Errors

An off-by-one error happens when your loop executes one too many or one too few times. This is the most common loop bug.

One Too Many
Using \(\le\) when you meant \(<\). E.g., printing indices 0 through 5 for a size-5 array causes an ArrayIndexOutOfBoundsException.
One Too Few
Using \(<\) when you meant \(\le\). E.g., summing 1 to n but stopping at n-1 because you wrote \(i < n\) instead of \(i \le n\).

Common Mistakes

✕ Missing Update
Forgetting to change the loop variable inside the body, causing an infinite loop.
✕ Wrong Operator
Using \(<\) instead of \(\le\) (or vice versa), causing an off-by-one error.
✕ Semicolon After while
Writing while(\(x < 5\)); puts an empty body. The real body never repeats.

Key Concepts Summary

Concept Description
Condition Boolean expression checked before each iteration
Body Code that executes when condition is true
Update Statement that changes the loop variable
Infinite loop Condition never becomes false: program hangs
Off-by-one Loop runs one too many or too few times
Sentinel Special value that signals the loop to stop
Zero iterations If condition is initially false, body never runs

Question 1 of 5

What is printed as a result of executing the code segment?

Question 2 of 5

What value is printed?

Question 3 of 5

Which of the following will cause an infinite loop?

Question 4 of 5

What value of b is printed?

Question 5 of 5

What value is printed?