In this article, you’ll learn about how to make a C++ in Program to Reverse an Array Using a Pointer with explanation.
What is an Array?
An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.
Program to reverse an array using a pointer in C++
#include <iostream>
using namespace std;
void reverseArray(int *arr, int size) {
int *start = arr;
int *end = arr + size - 1;
while (start < end) {
int temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Before Reversing: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
reverseArray(arr, size);
cout << "\nAfter Reversing: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
The reverseArray()
function takes two arguments: a pointer to an array and its size. Inside the function, we declare two pointers, start
and end
. start
points to the first element of the array and end
points to the last element of the array. We then loop through the array by swapping the values pointed to by start
and end
, and moving start
and end
pointers towards each other until they meet in the middle of the array. This effectively reverses the order of the elements in the array.
In the main()
function, we declare an array of integers arr
and its size size
. We then print the contents of the array before and after reversing it using the reverseArray()
function.
Output
Before Reversing: 1 2 3 4 5
After Reversing: 5 4 3 2 1
As you can see, the program successfully reverses the order of the elements in the array using pointers.