C Programming - Command Line Arguments - Discussion

Discussion Forum : Command Line Arguments - Find Output of Program (Q.No. 18)
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;
}
sample friday tuesday sunday
sample friday tuesday
sunday tuesday friday sample
sunday tuesday friday
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
11 comments Page 1 of 2.

Vishal said:   8 years ago
@Jyotir Mishra.

The "sample" is the name of the program. So the number of arguments is 4 not 5.

Jyotir Mishra said:   8 years ago
Hello friends.

I think the result will be some how like.

"sunday, tuesday friday sample mainProgram" bcz total no of argument is 5 not 4
sizeofargv=5 because. the first index of argv[] will point to the main program itself.
i.e ---->
argv[4] = sunday
argv[3] = tuesday
argv[2] = friday
argv[1] = sample
argv[0]---- main program.

Prakash said:   1 decade ago
Great yogesh.....

Narmada said:   1 decade ago
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].

Ferissa said:   1 decade ago
Hi pruthvi this is ferissa, I think there is no error when the program name matches with the argument.

Yogesh said:   1 decade ago
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.
(1)

Prudhvi said:   1 decade ago
Here sample is name of the program how can be it be an argument ?

Mani said:   1 decade ago
Thanks Arvind.

Arvind said:   1 decade ago
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

Pandi said:   1 decade ago
pls tell me about the detailed answer


Post your comments here:

Your comments will be displayed after verification.