Reverse an Array

Reverse an Array in C++

In this exercise, you will implement a program that reverses the order of elements within an array. Reversing data is a critical skill for tasks ranging from basic list manipulation to complex algorithm development like string processing or undo-mechanisms.

The strategy involves a "Two-Pointer" approach, where you swap elements from both ends moving towards the center. This exercise will strengthen your understanding of array indexing, loops, and in-place memory modification.

Logic Components

1. Two-Pointer Setup

We track the start (0) and end (size-1) indices to identify which elements to swap.

2. In-Place Swap

Using a temporary variable, we exchange values between the pointers without losing data.

3. Half-Iteration

The loop only runs until the middle (size / 2). Going further would reverse the array back to its original state.

Learning Objectives

  • 1. Master symmetrical indexing (mapping i to size - 1 - i).
  • 2. Implement the temporary swap pattern to avoid data loss.
  • 3. Optimize performance by iterating only n/2 times.
  • 4. Verify array state persistence after function execution.

Solution Implementation

reverse_array.cpp In-place Logic
#include <iostream>
using namespace std;

// Function to reverse an array by swapping elements
void reverseArray(int arr[], int size) {
    int temp; // Temporary container for swapping

    // Loop until the midpoint of the array
    for (int i = 0; i < size / 2; i++) {
        // Swap logic
        temp = arr[i];
        arr[i] = arr[size - 1 - i];
        arr[size - 1 - i] = temp;
    }
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    cout << "Original array: ";
    for (int i = 0; i < size; i++) cout << numbers[i] << " ";
    cout << endl;

    reverseArray(numbers, size);

    cout << "Reversed array: ";
    for (int i = 0; i < size; i++) cout << numbers[i] << " ";
    cout << endl;

    return 0;
}
Related Topics
In-Place Algorithms Two-Pointer Technique Element Swapping Space Complexity O(1) Reverse Iteration Time Complexity

Share this Training

Help your friends flip their C++ logic!

© C++ Programming Exercises. Master the art of performance coding.