What will be the output of the following code? #include <iostream> using…
2025
What will be the output of the following code?
#include <iostream>
using namespace std;
void func(int arr[], int left, int right)
{
while (left < right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1,4,3,5};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 0, n-1);
printArray(arr, n);
return 0;
}
- A.
5 1 4 3
- B.
3 5 1 4
- C.
5 3 4 1
- D.
error
Attempted by 8 students.
Show answer & explanation
Correct answer: C
Concept: In C++, an array parameter like arr[] decays to a pointer, so func(arr, left, right) operates directly on the caller's original array, not a copy. Repeatedly swapping arr[left] with arr[right] while incrementing left and decrementing right, until left is no longer less than right, swaps every pair of elements that sit equidistant from the two ends — which reverses the array in place.
Application: tracing the two-pointer swap on arr = {1, 4, 3, 5} with left = 0 and right = 3:
left = 0, right = 3: temp = arr[0] = 1; arr[0] = arr[3] = 5; arr[3] = temp = 1, so the array becomes {5, 4, 3, 1}; left becomes 1, right becomes 2.
left = 1, right = 2: temp = arr[1] = 4; arr[1] = arr[2] = 3; arr[2] = temp = 4, so the array becomes {5, 3, 4, 1}; left becomes 2, right becomes 1.
left = 2, right = 1: the condition left < right is now false, so the while loop stops.
printArray(arr, n) then prints the final array element by element, producing 5 3 4 1.
Cross-check: reversing {1, 4, 3, 5} directly — last element first, first element last, and the middle pair swapped — gives {5, 3, 4, 1}, matching the trace above. This is well-formed, standard C++ throughout (an array parameter decays to a pointer, and cout is available via <iostream>), so the program compiles and runs without error, ruling out that option too.