C++ (recursion with static indices and post-recursion swapping) — determine the final array order printed by Display().\n\n#include<iostream.h>\nstruct CuriousTabArray {\n int arr[5];\npublic:\n void CuriousTabFunction();\n void Display();\n};\nvoid CuriousTabArray::CuriousTabFunction() {\n static int i = 0, j = 4;\n i++; j--;\n if (j > 0) CuriousTabFunction();\n int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;\n i--; j++;\n}\nvoid CuriousTabArray::Display() {\n for (int i = 0; i < 5; i++) cout << arr[i] << " ";\n}\nint main() {\n CuriousTabArray objArr = {{5, 6, 3, 9, 0}};\n objArr.CuriousTabFunction();\n objArr.Display();\n return 0;\n}\n\nWhat output is produced?

Difficulty: Medium

Correct Answer: 0 6 3 9 5

Explanation:


Introduction / Context:
This problem checks your ability to trace a recursive function that uses static indices and performs its swap operations after unwinding recursion. The order of operations (pre-recursion index update, then post-recursion swap) is crucial to the final arrangement of the array elements.


Given Data / Assumptions:

  • Initial array: [5, 6, 3, 9, 0].
  • Static indices start at i = 0, j = 4.
  • Each call increments i, decrements j, recurses while j > 0, then swaps arr[i] and arr[j] while unwinding.


Concept / Approach:
Because the swap happens after recursion returns, the deepest frame swaps the ends first, then higher frames swap inner pairs, potentially swapping some positions back depending on indices restored by the static variables. Carefully tracking the evolving values of i and j is the key.


Step-by-Step Solution:

Deepest frame (after updates): swap indices 4 and 0 → [0, 6, 3, 9, 5]; i=3, j=1.Next: swap indices 3 and 1 → [0, 9, 3, 6, 5]; i=2, j=2.Next: swap indices 2 and 2 (no change) → remains [0, 9, 3, 6, 5]; i=1, j=3.Next: swap indices 1 and 3 → [0, 6, 3, 9, 5]; i=0, j=4.


Verification / Alternative check:
Compare with a version that performs the swap before recursion; it yields a different ordering (see next question for a variant).


Why Other Options Are Wrong:

  • Other sequences do not match the exact swap order based on post-recursion operations with static indices.


Common Pitfalls:
Forgetting that i and j are static and persist across frames; assuming each function activation has its own i, j.


Final Answer:
0 6 3 9 5

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion