Unit 2.7: while Loops
Iteration
Iteration is a form of repetition where a block of code is executed multiple times. Iteration statements, like the while loop, change the flow of control by repeating code as long as a Boolean expression remains true.
This mechanism is essential for:
- Processing collections of data: Going through every item in a list or array.
- Repeating actions: Asking for user input until valid data is provided.
- Automating calculations: Accumulating a sum or product over a range of numbers.
The while Loop
A while loop is a type of iteration statement that checks its condition before each execution of the loop block. The block will execute repeatedly as long as the condition is true.
- A
whileloop repeats code as long as a condition is true. It is ideal when you don't know the exact number of iterations in advance (e.g., waiting for specific user input).
The structure of a while loop typically involves three parts:
- Initialization: A loop control variable is initialized before the loop.
- Condition: The Boolean expression is checked before each iteration.
- Update: The loop control variable is updated inside the loop to eventually make the condition
false.
Task: Implementing a basic while loop.
public class WhileLoopDemo {
public static void main(String args[]) {
int x = 10; // 1. Initialization
while (x < 15) { // 2. Condition
System.out.println("Value of x: " + x);
x++; // 3. Update
}
}
}
When the Loop Body Does Not Execute
If the while loop's condition is false from the very beginning, the loop body will not execute even once.
Task: Observing behavior when the initial condition is false.
public class LoopSkipExample {
public static void main(String[] args) {
int count = 5;
while (count < 5) {
// This code is never reached because 5 is not less than 5.
System.out.println("This will not print.");
}
System.out.println("Loop is done.");
}
}
Infinite Loops
An infinite loop occurs when the loop's condition never becomes false.
- Every loop must have a path to termination. Infinite loops happen when the logic fails to update the state used in the condition, trapping the program in a never-ending cycle.
This is a common logic error that happens when the loop control variable is not updated correctly.
Task: Identifying an infinite loop logic error.
public class InfiniteLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println("This will print forever!");
// The variable 'i' is never updated, so i < 10 is always true.
}
}
}
Off-by-One Errors
An off-by-one error is a logic error where a loop runs one time too many or one time too few.
- Off-by-one errors are usually caused by a mismatch between the starting value and the comparison operator (
<vs<=). Precision at the boundaries is critical for correct algorithms.
This is often caused by an incorrect relational operator in the condition (e.g., using < when <= was needed).
Task: Identifying an off-by-one error in loop boundaries.
// Goal: Print numbers 1, 2, 3, 4, 5
public class OffByOneError {
public static void main(String[] args) {
int i = 1;
while (i < 5) { // ERROR: This condition stops the loop when i is 5.
System.out.println(i); // Will only print 1, 2, 3, 4
i++;
}
}
}
- The
do-whileloop, which checks its condition after the loop body, is not part of the AP Computer Science A course and will not be on the AP Exam.
Transition: Moving to for Loops
As you have seen, managing the three parts of a loop—initialization, condition, and update—separately can sometimes lead to errors like infinite loops or off-by-one errors. In the next section, we will explore the for loop, which simplifies this process by consolidating all three components into a single, compact line of code.