C++ recursion with a static accumulator and member mutation: what does this program print?\n\n#include<iostream.h>\nclass TestDrive\n{\n int x;\npublic:\n TestDrive(int xx) { x = xx; }\n int DriveIt(void);\n};\nint TestDrive::DriveIt(void)\n{\n static int value = 0; // accumulates across recursion\n int m;\n m = x % 2; // current parity bit\n x = x / 2; // shift right by 1 (integer divide)\n if ((x / 2)) DriveIt();\n value = value + m * 10;\n return value;\n}\nint main()\n{\n TestDrive TD(1234);\n cout << TD.DriveIt() * 10 << endl;\n return 0;\n}

Difficulty: Medium

Correct Answer: 400

Explanation:


Introduction / Context:
This program demonstrates recursion that peels bits off an integer while accumulating a result in a static local variable. Because the accumulator is static, its value persists across recursive calls and is updated during the unwind phase.


Given Data / Assumptions:

  • Initial member x = 1234.
  • At each call: m = x % 2; then x = x / 2.
  • Recursive step occurs if (x / 2) is nonzero.
  • After recursion, accumulator is updated: value = value + m * 10.
  • Final output multiplies DriveIt() by 10.


Concept / Approach:
Integer division by 2 shifts bits right. The test (x / 2) recurses as long as the result is nonzero, so the deepest frame corresponds to when x shrinks to 1 or 0. The update happens on unwinding—thus bits nearer the least significant positions contribute later. Multiplying by 10 at the end shifts the decimal-like accumulation one place to the left.


Step-by-Step Solution:
Trace x: 1234→617 (m=0), 308 (0), 154 (0), 77 (1), 38 (0), 19 (1), 9 (1), 4 (0), 2 (0), 1 (0). On unwind, value adds m*10 in order: 0, +0, +10, +10, +0, +10, +0, +0, +10, +0 = 40. DriveIt() returns 40; printing multiplies by 10 → 400.


Verification / Alternative check:
Run with a smaller number (e.g., 9) to see the same pattern: recursion depth follows division by 2, contributions occur after the recursive call.


Why Other Options Are Wrong:
200/300/100 result from miscounting the parity contributions; “Garbage value” is incorrect since control flow and returns are well-defined.


Common Pitfalls:
Confusing when the accumulator is updated (after recursion), and overlooking that value is static.


Final Answer:
400

More Questions from Functions

Discussion & Comments

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