reverse array in a function
To reverse an array in C++, you can create a function that takes the array as a parameter and modifies it in-place. Here is an example of how you can reverse an array in C++:
#include <iostream>
void reverseArray(int arr[], int size) {
int start = 0;
int end = size - 1;
while (start < end) {
// Swap elements at start and end indices
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move start and end indices towards the center
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
reverseArray(arr, size);
std::cout << "Reversed array: ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Let's go through the steps of the reverseArray
function:
- The function takes two parameters:
arr
, which is the array to be reversed, andsize
, which is the size of the array. - It initializes two variables,
start
andend
, to represent the start and end indices of the array. - It enters a loop that continues until the
start
index is less than theend
index. - Inside the loop, it swaps the elements at the
start
andend
indices using a temporary variabletemp
. - After swapping, it moves the
start
index one step forward and theend
index one step backward. - The loop continues until
start
is no longer less thanend
, which means the entire array has been reversed. - Finally, the reversed array is printed out using a
for
loop in themain
function.
When you run this program, it will output:
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
This demonstrates how the reverseArray
function reverses the elements of the array in-place.