C Programming - Command Line Arguments - Discussion

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

int main(int argc, char **argv)
{
    int i;
    for(i=0; i<argc; i++)
        printf("%s\n", argv[i]);
    return 0;
}
10 20 30
myprog 10 20
myprog 10 20 30
10 20
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
14 comments Page 1 of 2.

Devesh agarwal said:   1 decade ago
Does any have the explanation for this ?

Rabi said:   1 decade ago
The actual declaration of main command line is myprog "10" "20" "30" where each members of command line are string constant. Hence "10", "20", "30" are string constant not integer value. Hence there is no doubt of int value.

Vijeta said:   1 decade ago
Hey Rabi can you explain it in detail, I haven't understood.

Sudheer said:   1 decade ago
I thought, first argument is filename and later are normal arguments. So it prints filename first and later remaining arguments will be printed.

Puneet kaushik said:   1 decade ago
Please explain this question in detail. I haven't understood yet.

Nandu said:   1 decade ago
argv[0]=myprog
argv[1]=10
argv[2]=20
argv[3]=30

Here 1st i=0, it ll print whatever argv[0] have i.e, myprog.after print argv[0] value i ill increment to 1 because of i++. Now i=1, it print argv[1]=10 next i=2 and so on.

Wasim said:   1 decade ago
@Nandu.

But for loop is till i<argc so how 30 will print.

And **argv is pointer to pointer then how it treat as array ?

Adithya said:   1 decade ago
As @Wasim said the counter will loop till i=2 and then terminate so 30 does not get printed.

Abhirup said:   1 decade ago
Can some one elaborate this answer? Not getting why 30 is printed?

Hchank said:   10 years ago
The first argument to the main() (i.e int argc) is the total number of arguments passed at command line including the file_name so, here in this question argc = 4. You can check it by using printf ("%d", argc).

If you don't give any command line argument then, argc = 1 because of the file_name so, it will never be zero. So, the array subscript (index) will range from 0-3 and hence 30 gets printed.


Post your comments here:

Your comments will be displayed after verification.