Accumulation and Counting Patterns

Part of: Iteration

Loops That Build Up a Result Most useful loops fall into two patterns: accumulation (building a running total or product) and counting (tallying how many items match a rule). Recognizing these patterns lets you solve a huge range of problems quickly. The Accumulator Pattern An accumulator is a variable declared before the loop that collects a result inside the loop. The starting value matters: - For a sum , start the accumulator at 0. - For a product , start at 1. Starting a sum at 1 or a product at 0 is a common bug, the identity value must match the operation. The Counter Pattern A counter starts at 0 and increases only when a condition holds: Tracking a Running Best A close cousin is finding a maximum or minimum . Initialize a best-so-far variable, then update it whenever you find something better: Starting max at the smallest possible value guarantees the first real number replaces it. These three patterns, accumulate, count, and track-a-best, appear constantly, so practice spotting which one a problem needs.

Challenge: Factorial