Write a C++ program to reverse an Array.

Example:

There are multiple ways to reverse an array in C++. Let’s discuss each of them.

Reverse array in C++ using an Extra Array

  1. Intialize the input array with values.
  2. Declare a new empty array of the same size.
  3. Loop from back of the input array and assign its value from the stating of the new array.
  4. Output the reverse array.

output

Reverse array in C++ Without using an Extra Array

The logic to reverse an array without using another array in C++ is to swap 1st element with the last element, then the 2nd element with the 2nd last element, then 3rd, 4th… until we reach the middle element.

Reverse array without array

To do this we will use a while loop and two pointing variable i and j. i will point to the first index of the input array and j will point to the last index of the same array.

Inside while loop we will increment the value of ‘i’ (i++) and decrement the value of ‘j’ (j--), till the condition “i is less than j” satisfies.

Basically we are swapping the first element with the last, second element with the second last and so on.

See the full implementation in C++ below.

Reverse Array in C++ using Swapping

Output

Array reverse result

In the above method, we have not used any extra array to reverse an Array in C++, hence the method is quite space-efficient. Suggest in the comment box, if you know or want to get your method added in the post.

Leave a Reply