data-structures · intermediate · ~15 min
Index arithmetic with modular shifts.
Rotate the elements of an array to the right by k positions.
Implement void rotate_right(int *a, size_t n, size_t k) that rotates the n elements of a to the right by k positions, in place. Each element moves k slots toward the end, and elements pushed off the end wrap to the front. k may be larger than n.
a: writable array of n ints.n: the number of elements.k: the rotation amount (may exceed n; the effective shift is k % n).Nothing returned; a is rotated in place.
{1,2,3,4,5}, k=2 -> {4,5,1,2,3}
{1,2,3}, k=5 -> {2,3,1} (effective k = 5 % 3 = 2)
n == 0 or an effective shift of 0 leaves the array unchanged.k larger than n wraps via k % n.a: writable array of n ints; n; k (may exceed n).
Nothing returned; a is rotated right by k in place.
Effective shift is k % n; handle k >= n.
#include <stddef.h>
void rotate_right(int *a, size_t n, size_t k) { /* TODO */ }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.