Nested while Loops and Common Pitfalls
You'll learn how to place one while loop inside another and avoid the traps that often catch beginners.
What Are Nested while Loops?
A nested while loop is simply a while loop placed inside the body of another while loop. The inner loop executes completely for each single iteration of the outer loop. Think of it like the minute hand on a clock: for every hour (outer loop), the minute hand completes 60 full rotations (inner loop).
Basic Structure
while (outerCondition) {
// Outer loop body
while (innerCondition) {
// Inner loop body - runs completely each outer iteration
}
// More outer loop statements
}
Simple Example: Multiplication Table
int row = 1;
while (row <= 3) {
int col = 1;
while (col <= 3) {
System.out.print(row * col + " ");
col++;
}
System.out.println(); // New line after each row
row++;
}
This prints:
1 2 3
2 4 6
3 6 9
Common Pitfalls
1. Forgetting to reset the inner loop variable:
int col = 1; // Declared OUTSIDE - WRONG!
while (row <= 3) {
while (col <= 3) { // col never resets!
// Only runs once total
col++;
}
row++;
}
2. Modifying the wrong loop variable — always double-check which counter you're incrementing.
3. Unintended infinite loops — ensure both inner and outer conditions eventually become false.
Key Takeaway: Nested while loops require careful attention to variable scope—declare inner loop control variables inside the outer loop to reset them properly each iteration, and always verify both loop conditions can terminate.