The Accumulator Pattern
Here is the single most useful loop pattern in programming, and you already know both halves of it:
1. Create a variable before the loop to hold the result
2. Update it inside the loop with +=
3. Use it after the loop
Counting, summing, filtering, finding a maximum. They're all this pattern with a different body.
✦ Where total lives matters
total = 0 sits OUTSIDE the loop. Move it inside and it resets to zero on every pass, leaving you with only the last number. Initialize before, accumulate inside, use after, that order is the pattern.
Swap the body and the same skeleton filters, collecting only the items that pass a test.
Mark this lesson complete
Signed in, your progress follows you to every device.