In C, reversing traversal via argv index. Given the program below and execution: cmd> sample friday tuesday sunday, what exact contiguous output does it produce (note: printed without spaces or extra newlines)? /* sample.c */ #include<stdio.h> int main(int sizeofargv, char *argv[]) { while(sizeofargv) printf("%s", argv[--sizeofargv]); return 0; }

Difficulty: Medium

Correct Answer: sundaytuesdayfridaysample

Explanation:


Introduction / Context:
This question examines indexing from the end of the argv array and how decrementing the index inside the print statement affects order. It also highlights that no spacing or newline is added by the given printf calls, so results appear concatenated.


Given Data / Assumptions:

  • Command line: sample friday tuesday sunday
  • Parameters: int sizeofargv, char *argv[] (sizeofargv is used like argc).
  • Loop: while(sizeofargv) printf("%s", argv[--sizeofargv]);


Concept / Approach:
argv has elements argv[0]="sample", argv[1]="friday", argv[2]="tuesday", argv[3]="sunday". The code decrements the count first, then prints, so it begins from the last element and proceeds backward to 0, with no delimiters between prints.


Step-by-Step Solution:

Iteration 1: sizeofargv becomes 3 -> prints argv[3] = "sunday". Iteration 2: sizeofargv becomes 2 -> prints argv[2] = "tuesday". Iteration 3: sizeofargv becomes 1 -> prints argv[1] = "friday". Iteration 4: sizeofargv becomes 0 -> prints argv[0] = "sample". Concatenated output: sundaytuesdayfridaysample


Verification / Alternative check:
Adding a " " after %s would yield "sunday tuesday friday sample". Without that, it is contiguous.


Why Other Options Are Wrong:

  • samplefridaytuesdaysunday / samplefridaytuesday: Forward order, not reverse.
  • sundaytuesdayfriday: Omits argv[0].
  • fridaysundaysampletuesday: Wrong order.


Common Pitfalls:
Expecting spaces or newlines by default; printf("%s") does not add separators unless you include them.


Final Answer:
sundaytuesdayfridaysample

More Questions from Command Line Arguments

Discussion & Comments

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