C Workshop · Reverse an Array
Lesson C

Reverse an Array

Swap the first with the last, then move inward, until the middle.

What it is

Reversing in place means the same array turns around: first swaps with last, then you step inward, until you meet in the middle. No second array required.

Approach

  1. Store the n values.
  2. for i from 0 to n/2 - 1, swap a[i] and a[n-1-i].
  3. Print the array.

Where this is used in the real world

Diagram

1

1 2 3 4

start

2

swap 0↔3

4 2 3 1

3

swap 1↔2

4 3 2 1

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int a[4] = {1, 2, 3, 4};
4    int i, t;
5    for (i = 0; i < 2; i++) {
6        t = a[i];
7        a[i] = a[3 - i];
8        a[3 - i] = t;
9    }
10    printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
11    return 0;
12}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. 1 2 3 4 reversed is:

Swap 0↔3 then 1↔2.

2. Why stop at n/2?

Do not swap twice.

3. t holds:

Classic three-step swap.

4. In-place means:

No extra n boxes.

5. Strings reverse until:

Do not reverse the 0 byte into the middle.