Implementing Selection and Iteration · Implémentation de la sélection et de l'itération
| English | Français |
|---|---|
| accumulator/əˈkjuːmjʊleɪtə/ | accumulateur |
A zero initial maximum invents a result
- An array contains −8, −3 and −11. Starting max at zero leaves a maximum that was never in the array.
- For this nonempty array, start max at a[0]. Comparing the later values updates −8 to −3 and keeps it there.
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 · Commencer
sum = 0, thensum = sum + xinside the loop; the running total changes; it can decrease when a negative value is added. Same idea for a running count · compte (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, andif (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. Check the array is nonempty, startmaxat its first value, then examine the rest. An unspecified “very small number” can still exceed every actual input. if (x > max) { max = x; }inside the loop. After the loop,maxholds the largest value seen.
The accumulator pattern · Le motif de l'accumulateur
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 the innermost loop. A Boolean flag also needs to be used in the loop condition or control logic; merely assigning it does not stop execution.
Early exit with a flag or break
- Sometimes you can stop early once you've found what you need. A
booleanflag can record “found it” and be checked by the loop condition; assigning the flag alone does not exit a loop.breakexits the innermost 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 · somme starts at 0, a product · produit at 1 (starting a product at 0 makes it always 0), a max at the first element after a nonempty check. An empty collection has no maximum unless the contract explicitly defines a separate outcome. And update it every matching iteration — a misplaced initialization inside the loop resets it each pass and ruins the total.
What is the maximum of the nonempty array {−8, −3, −11}?
−3 is the greatest actual element. Starting at 0 produces an invalid invented candidate.
Reading a[0] is a valid way to initialize a maximum for an empty array.
There is no first element in an empty array. Check the input or define a separate no-maximum outcome.
How many even numbers are in the int array {-8, -3, -11}?
Only -8 has remainder zero when divided by 2; negative values can be even too.
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.
Carry the reasoning to a new case
- An empty array has no first element and needs a separate contract or check.
- The initial value must suit the operation: sum zero, product one, maximum a valid starting candidate.
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.