Implementing Selection and Iteration
| English | Chinese | Pinyin |
|---|---|---|
| accumulator | 累加器 | lěi jiā qì |
Loop patterns: accumulate
- A loop pattern is a reusable recipe for a common task.
- The accumulator 累加器 pattern builds a running total or product across iterations.
- Start
sum = 0, thensum = sum + xinside the loop; the total grows. - Same idea for a running count (
count++) or a running max.
Conditionals inside loops
- Put an
ifinside a loop to act only on items that match. - "Count the even numbers": loop, and
if (x % 2 == 0) count++; - The loop visits every item; the
ifdecides which ones to process. - Combining selection and repetition is the heart of most algorithms.
Finding a maximum
- To find the largest value, keep a
maxvariable and update it when you see something bigger. - Start
maxat the first value (or a very small number), then loop. if (x > max) { max = x; }inside the loop.- After the loop,
maxholds the largest value seen.
Early exit with a flag or break
- Sometimes you can stop early once you've found what you need.
- A
booleanflag records "found it"; orbreakexits the loop immediately. - "Does the list contain a zero?" — stop at the first zero.
- Early exit saves work but keep the logic correct for the "not found" case.
Initialize the accumulator correctly, or every result is off. A sum starts at 0, a product at 1 (starting a product at 0 makes it always 0), a max at the first element or a very small value. And update it every matching iteration — a misplaced initialization inside the loop resets it each pass and ruins the total.
Counting evens in a loop over an array a:
int count = 0;for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) count++; }- The loop visits each element; the
ifcounts only the even ones.
Common loop patterns combine iteration and selection: an accumulator (sum += x, count, or running max) built across passes, with an if inside to process only matching items. Initialize the accumulator right (sum 0, product 1, max the first value), and consider an early exit (break/flag) once the answer is found.
The accumulator pattern
sum accumulates across passes; it starts at 0.
To build a running SUM in a loop, you should initialize the accumulator to...
A sum starts at 0; a product would start at 1.
To build a running PRODUCT, initialize the accumulator to...
Starting a product at 0 makes it always 0; start at 1.
To count even numbers while looping, you use...
The if selects which items the loop counts.
Putting the accumulator's initialization inside the loop resets it every pass.
Initialize before the loop, not inside it.
To stop a loop as soon as a target is found, you can use...
break exits immediately; a flag records 'found'.