Skip to main content

Reversing an Array

 In this post, we will learn "How to reverse an Array".

Let us start by taking an array as input from the user and then we will reverse it.

Steps to follow:

  • Move element at the first index to last, and element at last index to first
  • Move element at the second index to second last, and element at second last index to the second
  • and so on

Let's have a look at the code, how to do this work:


#include<iostream>
using namespace std;
int main()
{
    int arr[100], tot, i, j, temp;

    cout<<"Enter the Size for Array: ";
    cin>>tot;

    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];

    cout<<"\nThe Original Array is:\n";

    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    j = tot-1;

    for(i=0; i<j; i++, j--)
    {
        temp = arr[i];  //swaped first element with last element  
        arr[i] = arr[j];
        arr[j] = temp;
    }

    cout<<"\n\nThe Reverse of Given Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}

I hope you all understood the concept.
If you have any query drop a comment below.
Thank You!!

Comments