JAVA / CHAPTER 06
Iteration
IntermediateUse loops with clear bounds, progress, and accumulators.
By the end of this chapter
- Trace a for loop
- Maintain an accumulator
- Identify termination conditions
The idea
Loops repeat a controlled piece of work. A for loop exposes initialization, continuation testing, and update together. A while loop checks its condition before each iteration and may execute zero times. Trace the condition before the body rather than assuming the body always runs. For a loop over n positions beginning at zero, i < n usually visits exactly the valid indices.
An accumulator represents a result built so far. State what it means before the loop starts and after each update: total can mean the sum of all accepted values already examined. Separately identify how the loop makes progress. Without a change that eventually falsifies the condition, execution can continue indefinitely.
public class Main {
public static void main(String[] args) {
int total = 0;
for (int n = 1; n <= 5; n++) {
if (n % 2 == 1) total += n;
}
System.out.println(total);
}
}9
The loop examines one through five and adds only one, three, and five. The total changes only when the condition succeeds.
Try it yourself
Count the positive values in a fixed integer sequence, then test a sequence with no positive values.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING