Noise
The knob on A0 is held still, yet analogRead returns 502, 497, 503, 498. That jitter is noise: interference picked up by the wires and the supply, plus the converter's own error of up to ±2 steps.
Moving average
Each reading goes into an array, buf, at slot i. Then i moves on: 0, 1, 2, 3 and back to 0, so the newest reading always overwrites the oldest. This is called a ring buffer.
Line 3 kept a running total: 502 + 497 + 503 + 498 = 2000. Line 6 divides by N: avg = 500. Noise pushes some readings up and some down, so in a sum they partly cancel.
Reading 506 arrives. Line 3 takes the oldest, 502, out of the total and adds 506: 2000 − 502 + 506 = 2004. Line 4 overwrites slot 0, and the average becomes 501. Two sums per reading, however big N is.
More readings stream in. The raw numbers wander from 496 to 503; the average stays between 499 and 501. Averaging N readings cuts random noise by about √N: four readings halve it, sixteen cut it to a quarter.
Other smoothers, and the cost
Line 7 keeps an exponential moving average, ema. Each reading moves it a quarter of the way toward itself: reading 498 takes ema from 500.4 to 499.8. It needs no array, just one variable.
Now the knob turns and readings jump to about 540. avg climbs 510, 519, 531, 540: four readings, 0.4 s, to catch up. ema is slower still: 511, 517, 524, 528. Smoother always means slower.
One glitch reads 600. avg jumps to 555 for four readings; ema jumps to 550 and fades slowly. A median of the last three readings takes the middle one, 542: the spike simply disappears.
What happens
;; step 1/8 · noise
board Arduino Uno R3 (ATmega328P), knob on A0
ADC 10 bits: 0..1023, about 100 µs per analogRead
readings 502 497 503 498 (knob not moving)
noise wires and supply pick up interference;
the ADC itself is accurate to ±2 LSB (steps)
The readings are an illustrative example, not a recording: a held knob on a breadboard really does wander by a few steps, but the exact numbers here were chosen for the story. Every average, ema and median is computed from them exactly as the sketch does it. setup() calls addReading() 4 times before loop() starts, so the buffer is full before the average is used. Slots start at 0, so during those first calls avg is too low; the Arduino "Smoothing" example has the same start-up effect. setup() then sets ema = avg so the exponential average does not start from 0.