A circular buffer stores a queue inside a fixed array. When an index reaches the end, it wraps back to the beginning and reuses free space.
The array stays still
Instead of shifting items after every removal, keep indexes for the front and the next open position. Modular arithmetic makes those indexes circle through the array.
- front marks the oldest item.
- size tells how many items are stored.
- capacity is the fixed number of slots.
- The next index is (index + 1) % capacity.
Wrapping makes the line circular
capacity = 4
index = 0
for step in range(7):
print(index)
index = (index + 1) % capacity
# 0, 1, 2, 3, 0, 1, 2Circular buffers are useful for streaming data, recent event logs, audio samples, and producer-consumer systems with a known memory limit.
The main design choice is what to do when the buffer is full: reject new data, wait, or overwrite the oldest item.
Your tiny challenge
Draw four slots. Move an index forward six times using the wraparound formula. Then decide how you would detect a full buffer.
