This post will discuss how to reverse an array in C++.

Practice this problem

1. Using reverse() function

The recommended solution for reversing elements of the specified array is to use the reverse() method defined in the algorithm header file.

Download  Run Code

2. In-place Implementation

The standard solution is to read the elements from both ends of the array and swap them. This can be done in-place, as demonstrated below:

Download  Run Code

3. Using Stack

Another plausible way of reversing an array is to use the stack data structure. The idea is to push each array element into a stack. Then pop values from the stack one by one and assign each popped item back to the original array starting from the beginning.

Download  Run Code

4. Using Recursion

We can also use recursion for reversing an array. The logic remains the same as the in-place implementation discussed above, but requires O(n) extra space for the call stack.

Download  Run Code

 
Here is another recursive program that stores elements of the array into the call stack, and then put them back into the array in the correct order as the recursion unfolds.

Download  Run Code

5. Using Auxiliary Array

Finally, we can create an auxiliary array of the same type and size as the input array, fill it with elements from the original array in reverse order, and then copy the contents of the auxiliary array into the original one.

Download  Run Code