A loop on its own only repeats an action. What makes loops useful is pairing them with a variable that survives from one pass to the next and gathers up the result — an accumulator. The loop supplies one value at a time; the accumulator remembers everything that has happened so far. Nearly every program that produces a total, an average, a count or a largest value is this one pattern wearing different clothes.
int[] marks = {78, 85, 92, 64};
int total = 0; // accumulator: declared OUTSIDE
for (int i = 0; i < marks.length; i++) {
total = total + marks[i]; // updated INSIDE
}
double average = (double) total / marks.length;
System.out.println("Total: " + total); // Total: 319
System.out.println("Average: " + average); // Average: 79.75| Pattern | Start at | Inside the loop | Why that start |
|---|---|---|---|
| Running total | int total = 0; | total += value; | Adding 0 changes nothing |
| Running product | int product = 1; | product *= value; | Multiplying by 1 changes nothing; 0 would trap it at 0 |
| Counting matches | int count = 0; | if (test) { count++; } | You have seen nothing yet |
| Largest value | int max = data[0]; | if (data[i] > max) { max = data[i]; } | The first element is the best candidate so far |
| Smallest value | int min = data[0]; | if (data[i] < min) { min = data[i]; } | Same reason, opposite comparison |
int[] temps = {-4, -11, -7, -2, -9}; // January in Ontario, in degrees Celsius
int max = temps[0]; // start at the FIRST element, not 0
for (int i = 1; i < temps.length; i++) { // start at 1: element 0 is already in max
if (temps[i] > max) {
max = temps[i];
}
}
System.out.println("Warmest: " + max); // Warmest: -2Nested loops
A nested loop is simply a loop written inside the body of another loop. One rule explains all of their behaviour: the inner loop runs completely, from its first pass to its last, for every single pass of the outer loop. The outer loop advances by one, and only then does the inner loop start over from the beginning. Rows and columns are the everyday picture — the outer loop chooses the row, the inner loop walks across it.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print(row * col + " ");
}
System.out.println(); // end the row: OUTER loop, not inner
}
// Output:
// 1 2 3 4
// 2 4 6 8
// 3 6 9 12for (int row = 1; row <= 5; row++) {
for (int star = 1; star <= row; star++) { // inner bound depends on row
System.out.print("*");
}
System.out.println();
}
// Output:
// *
// **
// ***
// ****
// *****Two keywords let you leave the normal loop rhythm. break abandons the loop immediately — no more passes, no update, and execution resumes at the first line after the loop. continue abandons only the current pass, jumping straight to the update and then the next condition test. In nested loops both affect only the loop they sit directly inside, so a break in the inner loop returns you to the outer loop rather than out of both. Use break to stop a search once the answer is found; if the exit rule can be written into the loop condition, write it there instead so a reader can see it.
int[] values = {4, 9, -1, 7, 12};
// continue: skip the negatives but keep going
int total = 0;
for (int i = 0; i < values.length; i++) {
if (values[i] < 0) {
continue; // skip the rest of THIS pass
}
total = total + values[i];
}
System.out.println(total); // 32 (4 + 9 + 7 + 12)
// break: stop as soon as the answer is found
int firstNegative = -1;
for (int i = 0; i < values.length; i++) {
if (values[i] < 0) {
firstNegative = i;
break; // leave the loop entirely
}
}
System.out.println(firstNegative); // 2