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; }

C++ Programming Objects and Classes Difficulty: Easy
Choose an option
  • A
    The program will print the output me!.
  • B
    The program will print the output Wel.
  • C
    The program will print the output !em.
  • D
    The program will print the output Welcome!.
  • E
    The 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 - 1 and decrements y each 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 = 0s[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.

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