In this tutorial, we will see how we can reverse an array in C++. So here goes the code:
Here when the 'reverseArray' function is called, it takes in the array and its size as the parameter. After that we set 'l' as left index and 'r' as right index. The while loop starts swapping the array with given indices, where the 'l' increases and 'r' decreases after each iteration. Thus when they reach the middle index two things happen:
1. If n is odd, the array has a mid point which is (n/2+1). In that case l=r and the loop stops.
2. If n is even, the array does not have a middle point, so we give the condition 'l<r' inside the while loop, so that the 'l' index does not increment after 'r'.
Output:
Original Array: 1,2,3,4,5,6,7,8,9.
Reversed Array: 9,8,7,6,5,4,3,2,1.