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:

  1. The function takes two parameters: arr, which is the array to be reversed, and size, which is the size of the array.
  2. It initializes two variables, start and end, to represent the start and end indices of the array.
  3. It enters a loop that continues until the start index is less than the end index.
  4. Inside the loop, it swaps the elements at the start and end indices using a temporary variable temp.
  5. After swapping, it moves the start index one step forward and the end index one step backward.
  6. The loop continues until start is no longer less than end, which means the entire array has been reversed.
  7. Finally, the reversed array is printed out using a for loop in the main 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.