C Programming - Command Line Arguments - Discussion

Discussion Forum : Command Line Arguments - Find Output of Program (Q.No. 16)
16.
What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample 1 2 3
cmd> sample 2 2 3
cmd> sample 3 2 3
/* sample.c */
#include<stdio.h>

int main(int argc, char *argv[])
{
    printf("%s\n", argv[0]);
    return 0;
}
sample 3 2 3
sample 1 2 3
sample
Error
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
14 comments Page 1 of 2.

Mounika said:   8 years ago
@Yogesh.

Here sample 1 2 3 all are command line arguments. It won't considers as program name then number of arguments and then the actual arguments.we just provide program name and arguments in cmd.

In main function, it only count the number of arguments and store it in argc and the arguments are stored in argv[ ] array.

So sample 1 2 3 are stored are argv[0],argv[1], argv[2], argv[3].

Hareesh naidu said:   10 years ago
/* sample.c */
#include<stdio.h>

int main(int argc, char *argv[])
{
printf("%s\n", argv[0]);
return 0;
}

In this problem we need to enter cmd> sample 1 2 3 this so here count is incremented argv[0] is sample, argv[1] is 1, argv[2] is 2.

And argv[3] is 3, so we want to printf argv[0] only so the string sample is printed by indexed wise.

Ravikanth said:   9 years ago
argv[0] it means take the first cmd prompt line sample 1 2 3
argv[0]=sample
argv[1]=1 so on

if you take next command line sample 1 2 3
+argv[0]= sample
+argv[1]=1 so on
similiar same third command line also

But our program print{argv[0]=sample}

So, the answer is sample.

Yogesh said:   8 years ago
We provide program name then number of arguments and then the actual arguments.

Here sample 1 2 3, means sample is program name, 1 means the number of arguments,
but we are providing 2 arguments i.e. 2 and 3, isn't it an error?

Santhoshi said:   1 decade ago
Hi friends here if want to print only argv[0] so that you print only sample suppose we want to print argv[1] then we print definitely 1 2 3.

Athul said:   1 decade ago
Here sample is the first argument so in each line of the command prompt we are calling sample 1 and printing it.

Nandhakumar said:   1 decade ago
Argv[0]=sample, no matter how many times you are called all are got overwritting.

Nandu said:   1 decade ago
Here argv[0]=sample, If he will give argv[1] then what will be the answer.

Sahil said:   8 years ago
It is so easy because it said arg[0], so on first place "sample" lies.

Soujanya said:   1 decade ago
argv[0] = sample and also see that %s specifies string not integer.


Post your comments here:

Your comments will be displayed after verification.