Welcome to the World of Iteration: The while Loop
Imagine you are teaching a robot to eat a bowl of cereal. You wouldn't tell the robot, "Eat 25 spoonfuls," because the bowl might be smaller or larger than that. Instead, you would say, "While the bowl is not empty, keep eating."
In computer science, this is called iteration or looping. It allows us to repeat a block of code multiple times without writing the same lines over and over. In this chapter, we focus on the while loop, the most fundamental type of iteration in Java.
Note: This chapter is part of Unit 2. Later, we will explore for loops (Topic 2.8) and nested iteration (Topic 2.11).
1. Anatomy of a while Loop
A while loop repeats a block of code as long as a specific boolean expression remains true. Here is the basic structure:
while ( boolean expression )
{
// Loop body: Code to repeat
}
There are three essential parts to making a loop work correctly:
1. Initialization: You set up a variable before the loop starts (e.g., \( count = 0 \)).
2. The Condition: The boolean expression that is checked before every "lap" of the loop. If it is true, the loop runs. If it is false, the loop stops.
3. The Update: A statement inside the loop body that changes the variable so that the condition eventually becomes false (e.g., \( count++ \)).
Quick Example:
int count = 1; // Initialization
while (count <= 3) // Condition
{
System.out.println("Hello!");
count++; // Update
}
Key Takeaway: If the condition is false the very first time it is checked, the code inside the loop will never execute!
2. How the Loop Executes (Step-by-Step)
Don't worry if this seems tricky at first! You can think of the computer as a runner on a circular track. Before every lap, the runner asks, "Am I allowed to run?"
1. The computer evaluates the boolean expression.
2. If the expression is true, the computer executes the entire body of the loop.
3. After the body is finished, the computer "loops back" to the top and evaluates the boolean expression again.
4. This repeats until the expression evaluates to false.
5. Once false, the computer skips the loop body and moves to the next line of code after the loop.
Did you know? In AP Computer Science A, we use postfix incrementing (\( x++ \)) to add 1 to a variable. The syllabus excludes prefix versions like \( ++x \), so stick to the standard \( x++ \) or \( x = x + 1 \) for your updates!
3. Tracing Code: The Trace Table
One of the most important skills for the AP Exam (especially Section I) is tracing. A trace table helps you keep track of variable values during each iteration.
Consider this code segment:
int x = 5;
int total = 0;
while (x > 0)
{
total = total + x;
x = x - 2;
}
Trace Table:
- Initial: \( x = 5 \), \( total = 0 \)
- Check Condition: Is \( 5 > 0 \)? Yes.
- Iteration 1: \( total = 0 + 5 \text{ (is 5)} \), \( x = 5 - 2 \text{ (is 3)} \).
- Check Condition: Is \( 3 > 0 \)? Yes.
- Iteration 2: \( total = 5 + 3 \text{ (is 8)} \), \( x = 3 - 2 \text{ (is 1)} \).
- Check Condition: Is \( 1 > 0 \)? Yes.
- Iteration 3: \( total = 8 + 1 \text{ (is 9)} \), \( x = 1 - 2 \text{ (is -1)} \).
- Check Condition: Is \( -1 > 0 \)? No. Loop terminates.
Final Values: \( x = -1 \), \( total = 9 \).
4. Common Pitfalls to Avoid
A. The Infinite Loop
An infinite loop occurs when the boolean expression never becomes false. This usually happens because the programmer forgot to update the variable or updated it in the wrong direction.
Example: If you have \( x = 5 \) and the condition is \( x > 0 \), but you use \( x++ \) inside the loop, \( x \) will keep getting larger and the loop will never stop!
B. Off-by-One Errors
This happens when the loop runs one time too many or one time too few. This is usually caused by using the wrong relational operator (\( < \) instead of \( <= \)).
C. Semicolon Errors
Never put a semicolon immediately after the while condition:
while (x < 10); // This creates an empty loop body, which often leads to an infinite loop!
5. Using while Loops with Strings
You will often use while loops to inspect or "traverse" a String. Since String indices start at \( 0 \) and go to \( length() - 1 \), your loop usually looks like this:
String str = "Java";
int i = 0;
while (i < str.length())
{
System.out.println(str.substring(i, i + 1));
i++;
}
Quick Review: Remember that \( substring(i, i + 1) \) returns exactly one character at index \( i \). The loop runs as long as \( i \) is less than the length of the string.
Chapter Summary
- A while loop is used for repetition when you don't necessarily know exactly how many times the loop will run.
- The condition must be a boolean expression.
- If the condition is true, the loop runs; if false, it stops.
- Always ensure the loop has an update statement to avoid infinite loops.
- Tracing is the best way to verify what a loop is doing.