In today’s fast – paced digital era, having a good command over programming languages proves to be quite beneficial for an individual. C++ is one such high – in – demand language, which is having a quite crucial value. In this article, you’ll be learning how you can reverse an Array in C++.
Given an array arr[] of elements (integers) Array arr[] : 1, 5, 7, 8, 9, 2, 3, 11
After reversal, the new array arr[] will be Array arr[]: 11, 3, 2, 9, 8, 7, 5, 1
Approach
- Consider 2 pointers start and end. Start will initially point to beginning of the array and end will point to end of the array.
- Swap the elements of the start and end positions.
- Increment the start pointer and decrement the end pointer.
- Repeat the process until start is greater or equal to the end pointer.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class ReverseArray
{
public:
//Method to reverse the array
void reverseArray(vector &arr, int size)
{
//checking if array size is 1 or 0
if(size == 0 || size == 1) return;
//initialising start with 0
int start = 0;
//initialising end with size of array -1 as index start from 0
int end = size - 1;
//looping through while start is less than end
while(start < end)
{
//swapping the values
swap(arr[start],arr[end]);
//increment start
start++;
//decrement end
end--;
}
}
//method to print elements of vector
void printVector(vector&arr, int arr_size)
{
for(int i=0;i<arr_size;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
};
int main()
{
//creating the ReverseAray object
ReverseArray ra;
vector arr = {1,4,3,5,7,8,9,8,2,6};
int arr_size = arr.size();
cout<<"Before Reversal"<<endl;
ra.printVector(arr, arr_size);
ra.reverseArray(arr, arr_size);
cout<<"After Reversal"<<endl;
ra.printVector(arr, arr_size);
return 0;
}
Output:
Before Reversal
1 4 3 5 7 8 9 8 2 6
After Reversal
6 2 8 9 8 7 5 3 4 1