Iteration with while and for Loops
Write and trace while loops, for loops, nested loops, loop bounds, accumulation, counting, sentinel patterns, and off-by-one cases.
A lesson of AP Computer Science A, in Control Flow and Methods, about 10 minutes.
Iteration: while and for Loops
By the end of this lesson, you will be able to write and trace while and for loops, avoid infinite loops, and select the appropriate loop for a given task.
The while Loop
while (condition) {
// body — executes while condition is true
// MUST update the condition variable to avoid infinite loop!
}
Trace: sum 1 to 5
int sum = 0, i = 1;
while (i <= 5) {
sum += i;
i++;
}
// sum = 15
do-while: the body always executes at least once (condition checked after).
do {
// body (runs at least once)
} while (condition);
The for Loop
for (initialization; condition; update) {
// body
}
All three parts are optional (but the semicolons are required).
Count from 1 to 5:
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
// Output: 1 2 3 4 5
Count down:
for (int i = 10; i > 0; i -= 2) {
System.out.print(i + " ");
}
// Output: 10 8 6 4 2
Common Loop Patterns
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
Find a sum:
Find a maximum:
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
Count elements meeting a condition:
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) count++;
}
Nested Loops
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print("* ");
}
System.out.println();
}
The inner loop completes fully for each iteration of the outer loop.
Output:
* * * *
* * * *
* * * *
Total iterations of inner loop body: 3 × 4 = 12.