c++ program to reverse an array
#include <iostream>
using namespace std;
void reverseArray(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, size);
reverseArray(arr, 0, size - 1);
cout << "Reversed array: ";
printArray(arr, size);
return 0;
}
Explanation:
reverseArray
function takes three arguments: the array to be reversed (arr[]
), the starting index (start
), and the ending index (end
). It reverses the elements within the specified range using a while loop.printArray
function simply prints the elements of the array passed to it.- In
main
function: - An array
arr
is initialized with values{1, 2, 3, 4, 5}
. size
variable stores the size of the array usingsizeof
.- The original array is printed using the
printArray
function. - The
reverseArray
function is called with the array, starting index0
, and ending indexsize - 1
. - The reversed array is printed using the
printArray
function.