Program : Reverse the Elements of an Array Without Additional Memory in C++
Solution :
Sometime, you see this problem as “Reverse the elements of an array in-place”. Here, “in-place” means that the original array is modified directly, without using additional arrays or data structures.
#include <iostream>
using namespace std;
int main() {
const int size = 5; // Change the size to fit your array
int arr[size],i;
int start = 0, end = size - 1,temp;
cout << "Enter " << size << " elements of an array : ";
for (i = 0; i < size; i++) {
cin >> arr[i];
}
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++; // Move start index towards the center
end--; // Move end index towards the center
}
cout << "Reversed array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output
Enter 5 elements of an array: 10 12 33 4 35 Reversed array : 35 4 33 12 10
Dry Run :
| start | end | start<end | temp=arr[start] | arr[start]=arr[end] | arr[end]=temp | start++ | end– |
| 0 | 4 | True | temp=10 | arr[0]=35 | arr[4]=10 | 1 | 3 |
| 1 | 3 | True | temp=12 | arr[1]=4 | arr[3]=12 | 2 | 2 |
| 2 | 2 | False | ———- | ——– | ——– | ——– | ——– |
So, from the above table, final value of array is 35 4 33 12 10.
Want to practice more problems involving Array 1-D ? Click here.