C Programming - Command Line Arguments - Discussion

18. 

What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample friday tuesday sunday

/* sample.c */
#include<stdio.h>

int main(int sizeofargv, char *argv[])
{
    while(sizeofargv)
        printf("%s", argv[--sizeofargv]);
    return 0;
}

[A]. sample friday tuesday sunday
[B]. sample friday tuesday
[C]. sunday tuesday friday sample
[D]. sunday tuesday friday

Answer: Option C

Explanation:

No answer description available for this question.

Balaji M said: (Dec 10, 2010)  
I need explanation regarding your answer.

Pandi said: (Dec 17, 2010)  
pls tell me about the detailed answer

Arvind said: (Feb 22, 2011)  
The first parameter inside main() contains the number of command line arguments. so sizeofargv = 4.
The second parameter inside main() contains the command line arguments as an array of string. so
*argv[3] = sunday
*argv[2] = tuesday
*argv[1] = friday
*argv[0] = sample

Mani said: (Jun 23, 2011)  
Thanks Arvind.

Prudhvi said: (Jul 20, 2011)  
Here sample is name of the program how can be it be an argument ?

Yogesh said: (Aug 27, 2011)  
The first parameter inside main(....)determines the number of cmd line arguments i.e sizeofargv=4.
and second parameter stores the actual parameters in array
i.e.
argv[3] = sunday
argv[2] = tuesday
argv[1] = friday
argv[0] = sample

while loop executed four times. It breaks when value of sizeofargv becomes -1.
Output:
in first execution: argv[3]=sunday
in second execution: argv[2] =tuesday
in third execution: argv[1]=friday
in fourth execution argv[0]=sample
now value of sizeofargv becomes -1 and loop breaks.

Ferissa said: (Sep 12, 2011)  
Hi pruthvi this is ferissa, I think there is no error when the program name matches with the argument.

Narmada said: (Nov 2, 2011)  
Pruthvi in c for command line arguments the program name will be consider as first argument as argv[0]. So sample will be stored in argv[0].

Prakash said: (Dec 10, 2011)  
Great yogesh.....

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.