In C++ (recursion with a static index over a C-string), what does the following program print when searching for the character 't' in the message "Welcome to CuriousTab.com!"?
#include
#include
class CuriousTab
{
char txtMsg[50];
public:
CuriousTab(char *str = NULL)
{
if(str != NULL)
strcpy(txtMsg, str);
}
int CuriousTabFunction(char ch);
};
int CuriousTab::CuriousTabFunction(char ch)
{
static int i = 0;
if(txtMsg[i++] == ch)
return strlen((txtMsg + i)) - i;
else
return CuriousTabFunction(ch);
}
int main()
{
CuriousTab objCuriousTab("Welcome to CuriousTab.com!");
cout << objCuriousTab.CuriousTabFunction('t');
return 0;
}
-
A6
-
B8
-
C9
-
D15
-
E16
Answer
Correct Answer: 8
Explanation
Introduction / Context: This C++ program performs a recursive scan over a C-style string using a static index variable. It stops when the currently inspected character matches the target and then computes a value from the suffix length. The key concepts are pointer arithmetic, static local variables, and how pre/post increments affect the index used in expressions.
Given Data / Assumptions:
- Message text: "Welcome to CuriousTab.com!" (length 26 characters).
- Target character: 't' (lowercase) appears first in "to" at index 8 (0-based).
- Function logic: compare txtMsg[i] to ch, then i is incremented due to
i++.
Concept / Approach: The expression txtMsg[i++] == ch compares the current character, then increments i. On the match at index 8, i becomes 9. The function returns strlen(txtMsg + i) - i, i.e., the length of the suffix starting at position 9 minus 9. If the total length is N, the suffix length is N - 9, so the return value is (N - 9) - 9 = N - 18.
Step-by-Step Solution:
Let N = 26 for "Welcome to CuriousTab.com!" First 't' is at index 8; after comparison, i becomes 9 Return value = (N - 9) - 9 = 26 - 18 = 8Verification / Alternative check: Manually counting characters or printing strlen(txtMsg) confirms N = 26. The suffix beginning at index 9 ("o CuriousTab.com!") has length 17; 17 - 9 = 8, consistent with the formula.
Why Other Options Are Wrong:
- 6, 9, 15, 16: These ignore the effect of
i++in the condition or miscount the overall string length.
Common Pitfalls: Forgetting that i is static (it persists across recursive calls), and misunderstanding that i++ increments after the comparison, so the returned expression uses i = 9 on the first match.
Final Answer: 8