C++ substring printing with index and count: what is printed by GetData("Welcome!", 1, 3) given the loop logic?\n\n#include<iostream.h>\n#include<string.h>\nclass CuriousTab\n{\npublic:\n void GetData(char s, int x, int y)\n {\n int i = 0;\n for (i = x - 1; y > 0; i++)\n {\n cout << s[i];\n y--;\n }\n }\n};\nint main()\n{\n CuriousTab objCuriousTab;\n objCuriousTab.GetData((char)"Welcome!", 1, 3);\n return 0;\n}

Difficulty: Easy

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.

More Questions from Objects and Classes

Discussion & Comments

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