C++ substring printing with index and count: what is printed by GetData("Welcome!", 1, 3) given the loop logic?
#include
#include
class CuriousTab
{
public:
void GetData(char s, int x, int y)
{
int i = 0;
for (i = x - 1; y > 0; i++)
{
cout << s[i];
y--;
}
}
};
int main()
{
CuriousTab objCuriousTab;
objCuriousTab.GetData((char)"Welcome!", 1, 3);
return 0;
}
-
AThe program will print the output me!.
-
BThe program will print the output Wel.
-
CThe program will print the output !em.
-
DThe program will print the output Welcome!.
-
EThe program will result in a compile time error.
Answer
Correct Answer: The program will print the output Wel.
Explanation
Introduction / Context:This checks basic index arithmetic and loop control for printing a slice of a C-string using a 1-based starting position and a count of characters.
Given Data / Assumptions:
- String:
"Welcome!". x = 1(1-based start index).y = 3(number of characters to print).- Loop starts at
i = x - 1and decrementsyeach iteration.
Concept / Approach:Since C arrays are 0-indexed, using i = x - 1 points to the intended start character. The loop prints exactly y characters from that position.
Step-by-Step Solution:Compute start index: i = 1 - 1 = 0 ⇒ s[0] = 'W'.First iteration prints W, y becomes 2.Second iteration prints e, y becomes 1.Third iteration prints l, y becomes 0 and loop ends.Combined output is Wel.
Verification / Alternative check:Try x=4, y=3 to see com, confirming the indexing logic.
Why Other Options Are Wrong:me! and !em are reversed slices; Welcome! prints the entire string, not a 3-character prefix; no compile error occurs.
Common Pitfalls:Off-by-one errors when converting from 1-based to 0-based indices; forgetting to bound the loop can cause overruns (not the case here).
Final Answer:The program will print the output Wel.