In C, printing the first character of each user argument. For the program below executed as: cmd> myprog one two three, what does it print (characters are contiguous, no spaces)?
/* myprog.c */
#include
int main(int argc, char *argv[])
{
int i;
for(i = 1; i < argc; i++)
printf("%c", argv[i][0]);
return 0;
}
-
Aoot
-
Bott
-
Cnwh
-
Deoe
-
Etto
Answer
Correct Answer: ott
Explanation
Introduction / Context: This problem checks array-of-strings indexing through argv and character indexing within each string. The program prints the first letter of each user-supplied argument in order.
Given Data / Assumptions:
- Arguments: one, two, three.
- Loop: i from 1 to argc - 1.
- Character printed: argv[i][0] (first character of each argument).
Concept / Approach: argv is an array of char*; argv[i] is a pointer to the i-th C string. Index zero selects the first character of that string. Concatenation results from printing with %c and no separators.
Step-by-Step Solution:
For "one": first character 'o'. For "two": first character 't'. For "three": first character 't'. Concatenated output: "ott".Verification / Alternative check: Changing the format to "%c " would show "o t t " with spaces; the characters are the same in order.
Why Other Options Are Wrong:
- oot: That would require "o", "o", "t".
- nwh / eoe: These pick other letters (e.g., second or third letters).
- tto: Wrong order.
Common Pitfalls: Accidentally starting the loop at i=0 prints the first letter of argv[0] (program name) too; here we intentionally start at the first user argument.
Final Answer: ott