C++ (recursion with static indices and pre-recursion swapping) — determine the array order produced and printed.
#include
struct CuriousTab {
int arr[5];
public:
void CuriousTabFunction(void);
void Display(void);
};
void CuriousTab::Display(void) {
for (int i = 0; i < 5; i++) cout << arr[i] << " ";
}
void CuriousTab::CuriousTabFunction(void) {
static int i = 0, j = 4;
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
i++; j--;
if (j != i) CuriousTabFunction();
}
int main() {
CuriousTab objCuriousTab = {{5, 6, 3, 9, 0}};
objCuriousTab.CuriousTabFunction();
objCuriousTab.Display();
return 0;
}
What output is produced?
-
A0 9 3 6 5
-
B9 3 6 5 0
-
C5 6 3 9 0
-
D5 9 3 6 0
-
ENone of the above
Answer
Correct Answer: 0 9 3 6 5
Explanation
Introduction / Context:This follow-up uses the same static-index idea but performs the swap before recursion. The base condition is j != i, so recursion stops when the two indices meet at the center. You must trace the swaps carefully with persistent i, j to get the final array ordering.
Given Data / Assumptions:
- Initial array:
[5, 6, 3, 9, 0]. - Static
i = 0,j = 4. - Each call swaps
arr[i]witharr[j], then incrementsiand decrementsj.
Concept / Approach:Because the swap occurs immediately, we reverse pairs from the outermost inward, then stop when i == j. With static variables, each recursive frame sees updated indices rather than independent copies.
Step-by-Step Solution:
Call 1: swap 0↔4 →[0, 6, 3, 9, 5]; then i=1, j=3; recurse (1 != 3).Call 2: swap 1↔3 → [0, 9, 3, 6, 5]; then i=2, j=2; stop (2 == 2).Display prints: 0 9 3 6 5.Verification / Alternative check:Compare with the variant that swaps after recursion; you will notice the middle positions differ because of the different order of operations.
Why Other Options Are Wrong:
- Other sequences do not match the exact swap-before-recursion trace.
Common Pitfalls:Thinking that recursion will reverse the entire array including the center twice; the stopping condition prevents that.
Final Answer:0 9 3 6 5