The idea
Count matches as you go
Like summing, you keep an accumulator — but this time it stores how many times something appears, not a running sum of values.
Initialise count = 0. For each index, if arr[i] equals the target, increase count by one.
TipCompare with linear search: search stops at the first hit; counting visits the whole list.
IdeaCounter loop
count_occurrences.pyPython
count = 0 for i in range(len(arr)): if arr[i] == target: count = count + 1
Array: [3, 5, 3, 8, 3, 1] · Target: 3 · Expected: 3
Interactive
Run the simulation
Boxes track i, target, and count. Green cells are matches already counted.
demo.pyPython
Array + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember
Counting vs searching
Same scan, different question.
Counter
Start at zero
Only increase count when the current element matches the target.
Full scan
Visit every index
Unlike search, you keep going after a match so you do not miss later ones.
Zero OK
No matches → 0
If nothing equals the target, count stays 0 — that is a valid answer.