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:
"Welcome!"
.x = 1
(1-based start index).y = 3
(number of characters to print).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 = 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.
Discussion & Comments