Array Patterns

Lesson 10 of 20

Learn the loops you will write forever: running sums, max scans, counting matches and reversing in place.

The big picture

Patterns you will reuse forever

Most array code is four shapes in a trench coat: running totals, best-so-far scans, counting matches and two-index swaps.

Running total

total = total + a[i] inside a loop — sums, averages and shopping carts all start here.

Best so far

Keep a champion in a variable and replace it whenever a[i] beats it.

Two indexes

One finger at each end, walking inward — the heart of reversing and many searches.

Counting matches

A counter that grows by 1 each time a condition is true.