String reversal using indexing: what does this C program output after reading a line with gets and then printing characters in reverse order? #include<stdio.h> #include<string.h> int main() { char sentence[80]; int i; printf("Enter a line of text "); gets(sentence); for (i = strlen(sentence) - 1; i >= 0; i--) putchar(sentence[i]); return 0; } Identify the correct behavior.
-
AThe sentence will get printed in same order as it entered
-
BThe sentence will get printed in reverse order
-
CHalf of the sentence will get printed
-
DNone of above
-
EProgram does not compile
Answer
Correct Answer: The sentence will get printed in reverse order
Explanation
Introduction / Context:This question verifies knowledge of iterating backwards through a C string using strlen and array indexing. The code demonstrates reversal by printing characters from the last index down to zero.
Given Data / Assumptions:
- sentence has space for up to 79 visible characters plus the null terminator.
- gets is used (unsafe) to read a line; it excludes the newline and appends '\0' at the end.
- strlen(sentence) returns the number of characters before the null terminator.
- putchar writes single characters in the loop.
Concept / Approach:The loop initializes i to strlen(sentence) - 1 (the last valid character index) and decrements down to 0 inclusive. This prints the string in reverse order.
Step-by-Step Solution:User enters text, e.g., "hello".strlen("hello") = 5, so start i = 4.putchar(sentence[4]) prints 'o', then i becomes 3 → prints 'l', then 2 → 'l', then 1 → 'e', then 0 → 'h'.Loop ends after i becomes -1, and the output is the reverse of the input.
Verification / Alternative check:Compare with using strrev (non-standard) or manual two-pointer reversal in a buffer; all produce the reversed text.
Why Other Options Are Wrong:Same order: would require forward iteration.Half printed: the loop clearly covers all indices down to 0.None of above / does not compile: the code compiles; logical behavior is reversal.
Common Pitfalls:Using gets (unsafe, buffer overflow risk); forgetting that strlen excludes the null terminator; off-by-one errors in start or end indices.
Final Answer:The sentence will get printed in reverse order