In C++ (recursive digit processing with a static accumulator), what number is printed for the initial value 12345?
#include
class CuriousTab
{
int Num;
public:
CuriousTab(int x)
{
Num = x;
}
int CuriousTabFunction(void);
};
int CuriousTab::CuriousTabFunction(void)
{
static int Sum = 0;
int Dec;
Dec = Num % 10;
Num = Num / 10;
if((Num / 100)) CuriousTabFunction();
Sum = Sum * 10 + Dec;
return Sum;
}
int main()
{
CuriousTab objCuriousTab(12345);
cout << objCuriousTab.CuriousTabFunction();
return 0;
}
-
A123
-
B321
-
C345
-
D12345
-
E54321
Answer
Correct Answer: 345
Explanation
Introduction / Context: This routine uses recursion and a static accumulator to process the decimal digits of an integer. The base case threshold (Num / 100) controls when to stop recursing, which affects how many trailing digits are accumulated and in what order during the unwind phase.
Given Data / Assumptions:
- Initial Num = 12345.
- Each call computes
Dec = Num % 10and then shrinksNum = Num / 10. - Recursive call happens while
Num / 100is nonzero (i.e., while Num >= 100). Sumis static across calls and updated after potential recursion.
Concept / Approach: The function pushes digits from right to left but only recurses while at least two digits remain (Num >= 100). Therefore, three least significant digits will be added during the unwind in the order encountered at return time, effectively yielding the last three digits of the original number in their original order (not fully reversed).
Step-by-Step Solution:
Call 1: Num=12345 → Dec=5, Num=1234 → recurse Call 2: Num=1234 → Dec=4, Num=123 → recurse Call 3: Num=123 → Dec=3, Num=12 → stop recursion (12/100 == 0) Unwind updates: Sum=0*10+3=3 → then 3*10+4=34 → then 34*10+5=345Verification / Alternative check: If the base condition were if(Num), the entire number would be reversed to 54321. With the current condition, only the lowest three digits contribute to the final Sum.
Why Other Options Are Wrong:
- 123 / 321 / 54321 / 12345: Do not reflect the specific stop condition used here.
Common Pitfalls: Overlooking that Sum is static (retained across calls) and that it is updated after the optional recursive call, which determines the order of accumulation.
Final Answer: 345