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. What usually goes wrong. What you see What caused it How to fix it --- --- --- Every input prints 0 The product accumulator started at 0, so every multiplication staye

Challenge: Factorial