basics · beginner · ~15 min

Reverse array in place

Two-pointer technique on arrays.

Challenge

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

Task

Implement void reverse_array(int *a, size_t n) that reverses the first n elements of a in place. No main — the grader calls it.

Input

  • a: pointer to a writable int array.
  • n: the number of elements. May be 0.

Output

Nothing is returned. The array a is modified so element order is reversed.

Example

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

Edge cases

  • n = 0 or n = 1: leave the array unchanged. Guard against n-1 underflowing for unsigned n.

Rules

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

Input format

Pointer a to a writable int array and a length n (n may be 0).

Output format

Nothing returned; a is reversed in place.

Constraints

In place, no extra array; guard n < 2 so n-1 does not underflow.

Starter code

#include <stddef.h>

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

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