In C, the code below reverses the first user argument character-by-character using strlen and a countdown index. If executed as: cmd> sample one two three, what does it print?
/* sample.c */
#include
#include
int main(int argc, char *argv[])
{
int i = 0;
i += strlen(argv[1]);
while(i > 0)
{
printf("%c", argv[1][--i]);
}
return 0;
}
-
Athree two one
-
Bowt
-
Ceno
-
Deerht
-
Enoe
Answer
Correct Answer: eno
Explanation
Introduction / Context: This tests string indexing and off-by-one care when reversing a string. The loop begins with i equal to the length of argv[1] and decrements before indexing, ensuring the last valid index is printed first.
Given Data / Assumptions:
- argv[1] is "one".
- i starts at strlen("one") = 3.
- Loop prints argv[1][--i] until i == 0.
Concept / Approach: Using pre-decrement inside the subscript shifts i from 3 to 2 for the first character printed, so the sequence of indices is 2, 1, 0 mapping to 'e', 'n', 'o' respectively, yielding the reverse string "eno".
Step-by-Step Solution:
First iteration: i=3 -> --i -> 2 -> prints 'e'. Second iteration: i=2 -> --i -> 1 -> prints 'n'. Third iteration: i=1 -> --i -> 0 -> prints 'o'. Stop when i becomes 0.Verification / Alternative check: Rewriting the loop to run i from strlen-1 down to 0 with i-- prints the same characters in the same order.
Why Other Options Are Wrong:
- owt / eerht: Those are reversals of "two" or "three", not "one".
- three two one: The program prints characters of argv[1] only, not words.
- noe: That is an incorrect reordering.
Common Pitfalls: Using post-decrement in the wrong place (argv[1][i--]) can cause off-by-one errors or print an extra character beyond bounds.
Final Answer: eno