Reverse an array in C++

C++Server Side ProgrammingProgramming

The article showcase an array to be reversed in descending order using the C++ coding wherein the highest index is swapped to lowest index consequently by traversing the array in the loop.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int arr[], int n){
   for (int low = 0, high = n - 1; low < high; low++, high--){
      swap(arr[low], arr[high]);
   }
   for (int i = 0; i < n; i++){
      cout << arr[i] << " ";
   }
}
int main(){
   int arrInput[] = { 11, 12, 13, 14, 15 };
   cout<<endl<<"Array::";
   for (int i = 0; i < 5; i++){
      cout << arrInput[i] << " ";
   }
   int n = sizeof(arrInput)/sizeof(arrInput[0]);
   cout<<endl<<"Reversed::";
   reverseArray(arrInput, n);
   return 0;
}

Output

As the integer type of array supplied in a bid to be reversed in descending order, the following yields as ;

Array::11 12 13 14 15
Reversed::15 14 13 12 11
raja
Published on 23-Dec-2019 10:51:32
Advertisements