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

C Programming Command Line Arguments Difficulty: Easy
Choose an option
  • A
    sample monday tuesday wednesday thursday
  • B
    monday tuesday wednesday thursday
  • C
    monday tuesday thursday
  • D
    tuesday

Answer

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