basics · beginner · ~15 min

Reverse an array in place

Swap from both ends toward the middle.

Challenge

Reverse an array in place using two indices that meet in the middle.

Task

Implement void reverse_array(int *a, int n) that reverses the order of the first n elements of a, modifying the array in place (no extra array). Use two indices, one from each end, swapping and moving inward. No main — the grader calls it.

Input

A pointer a to at least n ints, and the count int n (n >= 0).

Output

No return value. After the call, the first n elements are in reversed order.

Example

{1,2,3,4}   ->   {4,3,2,1}
{1,2,3}     ->   {3,2,1}
{9}         ->   {9}

Edge cases

  • A single-element (or empty) array is unchanged.

Rules

  • Reverse in place — do not allocate a second array.

Input format

A pointer a to n ints, and the count int n (n >= 0).

Output format

No return value; the first n elements are reversed in place.

Constraints

Reverse in place; no auxiliary array.

Starter code

void reverse_array(int *a, int n) {
    /* TODO */
}

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