Fix the Integer Array Reversal Bug in C++
The given C++ function is intended to reverse the elements of an integer array in place, but it contains logical errors causing incorrect output or runtime issues. Your task is to identify and fix the bugs so the array is reversed correctly.
Challenge prompt
You are given a C++ function meant to reverse an integer array in place. However, the function currently produces incorrect results or runtime errors due to bugs in the code. Fix the function so that it correctly reverses the array elements without using extra memory. Example: Input: arr = {1, 2, 3, 4, 5} After calling reverseArray(arr, 5), arr should be {5, 4, 3, 2, 1} Analyze the code carefully, identify bugs, and correct them.
Guidance
- • Review the loop conditions and index calculations carefully to ensure you don’t access out of bounds elements.
- • Check the swapping logic to verify both elements are exchanged properly.
- • Remember that array indices in C++ start at 0, so the last element is at size - 1.
Hints
- • Pay close attention to the loop boundary; it should only iterate halfway through the array.
- • The swap should use a temporary variable to avoid overwriting values before swapping both elements.
- • Be sure not to increment or decrement indices in a way that skips elements or causes invalid access.
Starter code
void reverseArray(int arr[], int size) {
int start = 0;
int end = size;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}Expected output
For input: {10, 20, 30, 40, 50} After reverseArray call: {50, 40, 30, 20, 10}
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.