How to Reverse the Elements of an Array in C++

In this tutorial, we will learn about  How to reverse the elements of an array in C++. Let us start with algorithm.

Algorithm to reverse elements of a given array in C++

  1. Let A be array to be reversed with n number of elements.
  2. Define two indexes i and j pointing first and last element of an array:[i=0, j=n-1].
  3. Repeat the loop for n/2 number of times.
  4. In each iteration, swap the array elements pointed by pointer i and j.
  5. After swapping modifies indexes as i=i+1and j=j-1.

In this program, we use the function like reverseArray, printArray. In this reverseArray, we swap the two numbers by using the temporary variable. In the printArray function, we display the output by using a for loop.

let us take an example input of array is  5 6 9 8 7 1

Output of array is 1 7 8 9 6 5. We can do this process by the above algorithm.

C++ Program to reverse array elements

#include<iostream>
using namespace std;
void reverseArray(int a [], int n)
{
  int i,j,temp;
  for(i=0,j=n-1;i<n/2;i++,j--)
  {
    temp=a[i];
    a[i]=a[j];
    a[j]=temp;
  }
}
void printArray(int a[], int n)
{
  int i;
  for(i=0;i<n;i++)
  {
    cout<<a[i]<<" ";
  }
}
int main()
{
  int a[100],n,i;
  cout<<"Enter n value \n";
  cin>>n;
  cout<<"Enter array elements \n";
  for(i=0;i<n;i++)
  {
    cin>>a[i];
  }
  cout<<"\n "<<"Array elements before reversing :\n";
  printArray(a,n);
  reverseArray(a,n);
  cout<<"Array elements after reversing :\n";
  printArray(a,n);
  return 0;
}

Output:

Enter n value
5
Enter array elements
 1 2 3 4 5

 Array elements before reversing :
1 2 3 4 5
Array elements after reversing :
5 4 3 2 1

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *