data-structures · beginner · ~15 min

Ring-buffer index

Use modular arithmetic for wrap-around indexing.

Challenge

Compute a wrapped index into a ring buffer.

Task

A queue backed by a ring buffer of capacity cap wraps around at the end. Implement int ring_index(int start, int k, int cap) that returns the buffer index k positions after start, wrapping past the end of the buffer.

Input

  • start: a valid starting index, 0 <= start < cap.
  • k: a non-negative offset (k >= 0), possibly larger than cap.
  • cap: the buffer capacity (cap > 0).

Output

int: the index k steps after start, wrapped into [0, cap).

Example

ring_index(2, 1, 8)   ->   3    (no wrap)
ring_index(6, 4, 8)   ->   2    (wraps past the end)
ring_index(3, 5, 8)   ->   0    (lands exactly on 0)

Edge cases

  • An offset of 0 returns start.
  • Offsets at or beyond cap wrap around.

Input format

start (0 <= start < cap), k (>= 0), cap (> 0).

Output format

int: index k positions after start, wrapped into [0, cap).

Constraints

Use modulo cap for the wrap-around.

Starter code

int ring_index(int start, int k, int cap) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.