Reverse an Array

Reverse an Array in C++ (7 Programs With Output)

C++Beginner
C++
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = 5;
    
    // Method 1: Using reverse() from algorithm
    int arr1[] = {1, 2, 3, 4, 5};
    reverse(arr1, arr1 + n);
    
    // Method 2: Using swap
    int arr2[] = {1, 2, 3, 4, 5};
    for (int i = 0; i < n / 2; i++) {
        swap(arr2[i], arr2[n - i - 1]);
    }
    
    cout << "Original array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    cout << "Reversed (method 1): ";
    for (int i = 0; i < n; i++) {
        cout << arr1[i] << " ";
    }
    cout << endl;
    
    cout << "Reversed (method 2): ";
    for (int i = 0; i < n; i++) {
        cout << arr2[i] << " ";
    }
    cout << endl;
    
    return 0;
}

Output

Original array: 1 2 3 4 5
Reversed (method 1): 5 4 3 2 1
Reversed (method 2): 5 4 3 2 1

This program teaches you how to reverse an array in C++. Reversing an array means changing the order of elements so that the first element becomes the last, the second becomes the second-to-last, and so on. For example, [1, 2, 3, 4, 5] becomes [5, 4, 3, 2, 1]. This is a fundamental array operation used in many algorithms and programming problems.


1. What This Program Does

The program reverses the order of elements in an array. For example:

  • Original array: [1, 2, 3, 4, 5]
  • Reversed array: [5, 4, 3, 2, 1]

The reversal swaps elements from both ends, moving toward the center until all elements are swapped.

Example:

  • [10, 20, 30] → [30, 20, 10]
  • [1, 2, 3, 4] → [4, 3, 2, 1]

2. Header Files Used

  1. #include <iostream>

    • Provides cout and cin for input/output operations.
  2. #include <algorithm>

    • Provides the reverse() function for reversing arrays/containers.
    • Contains many useful STL algorithms.

3. Declaring Variables

The program declares: int arr[] = {1, 2, 3, 4, 5}; int n = 5;

  • arr[] is an integer array containing 5 elements.
  • n stores the size of the array (5 elements).

4. Method 1: Using reverse() Algorithm (STL)

int arr1[] = {1, 2, 3, 4, 5}; reverse(arr1, arr1 + n);

This is the simplest and most recommended method:

  • reverse() is a built-in STL algorithm from <algorithm> header.
  • reverse(start, end) reverses elements in the range [start, end).
  • arr1 points to the first element, arr1 + n points past the last element.

How it works:

  • reverse() swaps elements from both ends toward the center.
  • Automatically handles the swapping logic.
  • Works with arrays, vectors, and other containers.

Advantages:

  • Simplest syntax
  • Built-in and optimized
  • Works with any container type
  • Most commonly used method

Example: int arr[] = {1, 2, 3, 4, 5}; reverse(arr, arr + 5); // arr is now [5, 4, 3, 2, 1]


5. Method 2: Using swap() in a Loop

int arr2[] = {1, 2, 3, 4, 5}; for (int i = 0; i < n / 2; i++) { swap(arr2[i], arr2[n - i - 1]); }

This method manually swaps elements:

  • Loop runs from 0 to n/2 (half the array).
  • Swaps element at position i with element at position (n - i - 1).
  • After n/2 swaps, the array is reversed.

How it works:

  • i = 0: swap arr[0] with arr[4] → [5, 2, 3, 4, 1]
  • i = 1: swap arr[1] with arr[3] → [5, 4, 3, 2, 1]
  • i = 2: (n/2 = 2, so loop stops - middle element stays)

Why n/2?

  • We only need to swap half the elements.
  • Swapping all elements would reverse it twice (back to original).

Advantages:

  • Clear logic - shows how reversal works
  • Educational - helps understand the algorithm
  • In-place reversal (no extra space needed)

6. Other Methods (Mentioned but not shown in code)

Method 3: Using Two Pointers

int left = 0, right = n - 1; while (left < right) { swap(arr[left], arr[right]); left++; right--; }

  • Uses two pointers starting from both ends.
  • Moves pointers toward center while swapping.
  • Stops when pointers meet or cross.

Method 4: Using Recursion

void reverseRecursive(int arr[], int start, int end) { if (start >= end) return; swap(arr[start], arr[end]); reverseRecursive(arr, start + 1, end - 1); }

  • Recursive approach - function calls itself.
  • Base case: when start >= end (pointers meet).
  • Recursive case: swap ends, then recurse on inner portion.

Method 5: Using Stack

stack<int> s; for (int i = 0; i < n; i++) s.push(arr[i]); for (int i = 0; i < n; i++) { arr[i] = s.top(); s.pop(); }

  • Uses stack's LIFO (Last In First Out) property.
  • Push all elements, then pop to get reversed order.

Method 6: Using Temporary Array

int temp[n]; for (int i = 0; i < n; i++) { temp[i] = arr[n - i - 1]; } for (int i = 0; i < n; i++) { arr[i] = temp[i]; }

  • Creates temporary array with reversed elements.
  • Copies back to original array.
  • Uses extra space O(n).

Method 7: Using Vector

vector<int> vec(arr, arr + n); reverse(vec.begin(), vec.end()); // Copy back if needed

  • Converts array to vector.
  • Uses vector's reverse() method.
  • More flexible but requires conversion.

7. Displaying Results

The program prints: cout << "Original array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; }

cout << "Reversed (method 1): "; for (int i = 0; i < n; i++) { cout << arr1[i] << " "; }

Output: Original array: 1 2 3 4 5 Reversed (method 1): 5 4 3 2 1 Reversed (method 2): 5 4 3 2 1

Both methods produce the same reversed array.


8. Understanding the Reversal Process

Visual Example (for [1, 2, 3, 4, 5]):

Initial: [1, 2, 3, 4, 5] ↑ ↑ start end

Step 1: [5, 2, 3, 4, 1] (swap 1 and 5) ↑ ↑ start end

Step 2: [5, 4, 3, 2, 1] (swap 2 and 4) ↑ ↑ start end

Done: [5, 4, 3, 2, 1] (middle element 3 stays)

Key Insight: Only need to swap n/2 pairs. Middle element (if odd length) doesn't move.


9. When to Use Each Method

  • reverse() Algorithm: Best for most cases - simple, optimized, recommended.

  • swap() in Loop: Good for learning - shows the algorithm clearly.

  • Two Pointers: Similar to swap method - clear and efficient.

  • Recursion: Educational - helps understand recursive thinking.

  • Stack: Demonstrates stack usage - educational purpose.

  • Temporary Array: When you need to preserve original - uses extra space.

  • Vector: When working with vectors or need dynamic size.

Best Practice: Use reverse() for most applications - it's simple, efficient, and works with any container.


10. Time and Space Complexity

Time Complexity:

  • All in-place methods: O(n) - need to process each element once.
  • reverse() algorithm: O(n) - optimized implementation.

Space Complexity:

  • In-place methods (reverse, swap, two pointers): O(1) - no extra space.
  • Temporary array method: O(n) - needs extra array.
  • Stack method: O(n) - needs stack space.
  • Recursion: O(n) - function call stack.

11. Common Use Cases

Algorithm Problems:

  • Rotating arrays
  • Palindrome checking
  • Two-pointer techniques
  • Array manipulation problems

Data Processing:

  • Reversing data for display
  • Processing arrays in reverse order
  • Undo/redo operations

Interview Questions:

  • Common coding interview problem
  • Tests understanding of arrays and algorithms
  • Foundation for more complex problems

12. Important Considerations

Array Bounds:

  • Always ensure indices are within bounds.
  • For swap method: n - i - 1 must be >= 0 and < n.

Odd vs Even Length:

  • Odd length: middle element stays in place.
  • Even length: all elements are swapped.
  • Algorithm handles both cases correctly.

In-place vs Copy:

  • In-place methods modify the original array.
  • If you need the original, make a copy first.
  • Temporary array method preserves original (if you copy back).

13. return 0;

This ends the program successfully.


Summary

  • Reversing an array swaps elements from both ends toward the center.
  • reverse() algorithm is the simplest and most recommended method.
  • swap() in a loop shows the algorithm clearly and is educational.
  • Only n/2 swaps are needed (half the array length).
  • In-place methods use O(1) extra space, temporary array uses O(n).
  • Understanding array reversal is essential for many array manipulation problems.
  • Choose the method based on your needs: simplicity vs. learning vs. space efficiency.

This program is fundamental for beginners learning array operations, understanding in-place algorithms, and preparing for more complex array manipulation problems in C++ programs.