Reverse an Array

Reverse an Array” is an elementary problem for beginners based on array data structure. Here, we are given an array containing ‘n’ elements and our task is to reverse given array.

Example:

```INPUT ARRAY:
Array[5] = {1, 2, 3, 4, 5}
OUTPUT ARRAY:
Array[5] = {5, 4, 3, 2, 1}

INPUT ARRAY:
Array[4] = {10, 20, 30, 40}
OUTPUT ARRAY:
Array[4] = {40, 30, 20, 10}```

The steps required to reverse an array elements are as follows:

1. Scan the array element.
2. Set two iterators, one pointing at first index position(0) of an array and other one pointing at last index position(n-1) of an array.
3. Now, in a loop, swap the elements arr[start] and arr[end] and then increment and decrement the iterators as follows:

Start = Start + 1

End = End – 1.

Loop will continue until End >= Start

C++ Program to reverse an array elements is as follows:

```/* C++ Program to Reverse an array */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;

/* Scan Array Size */
cout<<"Enter the number of array elements: ";
cin>>n;

/* Creating an Array */
int arr[n];

/* Scanning the array elements */
cout<<"\nEnter the array elements: ";
for(int i = 0; i < n; i++)
cin>>arr[i];

/* Printing the array element Before Reversing */
cout<<"\nThe array elements before reversing are: ";
for(int i = 0; i < n; i++)
cout<<arr[i]<<" ";

/* Reversing an Array element */
for(int i = 0, j = n - 1; j >= i; i++, j--)
{
int swap = arr[i];
arr[i] = arr[j];
arr[j] = swap;
}

/* Printing the array element After Reversing */
cout<<"\nThe array elements After reversing are: ";
for(int i = 0; i < n; i++)
cout<<arr[i]<<" ";
}

```
```OUTPUT:
Enter the number of array elements: 5
Enter the array elements: 1 2 3 4 5
The array elements before reversing are: 1 2 3 4 5
The array elements After reversing are: 5 4 3 2 1

Time Complexity:
O(n), for scanning, reversal and printing the array elements```

Related Posts: