Iterating over command-line arguments with pre-increment on argv pointer: what strings print?\n\n/* sample.c */\n#include <stdio.h>\n\nint main(int argc, char argv[])\n{\n / Invoked as: sample monday tuesday wednesday thursday */\n while (--argc > 0)\n printf("%s", *++argv);\n return 0;\n}\n

Difficulty: Easy

Correct Answer: monday tuesday wednesday thursday

Explanation:


Introduction / Context:
This question reinforces how argc and argv are commonly used to step through command-line arguments. The code decrements argc in the loop condition and advances the argv pointer before dereferencing, thereby skipping the program name and printing the remaining arguments in order.


Given Data / Assumptions:

  • Invocation: sample monday tuesday wednesday thursday.
  • Initial argc = 5; argv[0] = "sample"; argv[1..4] are the weekday strings.
  • printf uses "%s" without spacing; conceptually, the tokens are printed in sequence.


Concept / Approach:
The pattern while (--argc > 0) { printf("%s", *++argv); } is idiomatic. Pre-decrement drops the count to the number of remaining args, while pre-increment moves argv past argv[0] before dereference, so the loop prints argv[1], argv[2], argv[3], argv[4].


Step-by-Step Solution:

First iteration: argc = 4 → print argv[1] = "monday".Second: argc = 3 → print argv[2] = "tuesday".Third: argc = 2 → print argv[3] = "wednesday".Fourth: argc = 1 → print argv[4] = "thursday".


Verification / Alternative check:
Adding a space in the format string ("%s ") would make the separation explicit; the logical sequence remains the same.


Why Other Options Are Wrong:

  • Includes "sample": wrong because argv is advanced before printing.
  • Missing wednesday or starting at tuesday: contradicts the iteration.


Common Pitfalls:
Forgetting that *++argv both skips argv[0] and marches forward each iteration; confusing visual spacing with the underlying order.


Final Answer:
monday tuesday wednesday thursday

Discussion & Comments

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