Course contentsShow
← C
Lesson 440 of 1,2196. Arrays and StringsFree lesson

Reversing an array in place

Reversing an array in place

What you'll learn: How to flip the order of elements in an array without using a temporary "backup" array, saving memory and processing time.

The "Two-Pointer" Strategy

Imagine a row of numbered tiles on a table. To reverse them, you don't need to move them all to a second table. Instead, you put your left hand on the first tile and your right hand on the last tile. You swap them. Then, you move your hands inward—left hand to the second tile, right hand to the second-to-last—and swap again. You stop when your hands meet in the middle.

In C, we do this using two index variables (often called i and j or start and end). By swapping elements directly within the original memory space, we say the algorithm is "in place."

The Logic

To swap two variables in C, we need a tiny "parking space" (a temporary variable) so we don't overwrite a value before it's moved. If you have a cup of coffee and a cup of tea and want to swap the liquids, you need an empty third cup to hold the coffee momentarily.

We run a loop that continues as long as the start index is less than the end index. If we kept going after they met, we would just swap everything back to the original order!

Code Example

Here is how you implement an in-place reversal:

#include <stdio.h>

void reverseArray(int arr[], int size) {
    int start = 0;
    int end = size - 1;
    int temp;

    while (start < end) {
        // Step 1: Put the first value in the 'parking space'
        temp = arr[start];
        
        // Step 2: Move the end value to the start
        arr[start] = arr[end];
        
        // Step 3: Move the 'parked' value to the end
        arr[end] = temp;

        // Step 4: Move pointers toward the center
        start++;
        end--;
    }
}

int main() {
    int myNumbers[] = {10, 20, 30, 40, 50};
    int size = 5;

    reverseArray(myNumbers, size);

    // The array is now {50, 40, 30, 20, 10}
    return 0;
}

Why This Matters

Performing operations "in place" is a hallmark of efficient C programming. If you had an array with a million items, creating a second "backup" array would double your program's memory usage. The two-pointer approach uses only one extra integer of memory (temp) regardless of how large the array is.

Key takeaway

To reverse an array in place, swap the outer elements using a temporary variable and move inward until the indices meet.