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
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;
}
Discussion:
14 comments Page 1 of 2.
Ruku said:
7 years ago
Here the argc is 4.
So according to this;
for(i=0; i<argc; i++)
=>myprog 10 20 30 be the answer.
So according to this;
for(i=0; i<argc; i++)
=>myprog 10 20 30 be the answer.
Rit said:
8 years ago
If those are strings in loop what is the value of argc and how many times it will go?
Sealon said:
8 years ago
The argc is the number of paramters which is 4 (myprog, 10, 20,30), argv can be understood as *argv[4], regardless of the diffrence between pointer and array name.
Nani said:
10 years ago
I think in command line not allow the integer values. So it shows error.
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.
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.
Abhirup said:
1 decade ago
Can some one elaborate this answer? Not getting why 30 is printed?
Adithya said:
1 decade ago
As @Wasim said the counter will loop till i=2 and then terminate so 30 does not get printed.
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 ?
But for loop is till i<argc so how 30 will print.
And **argv is pointer to pointer then how it treat as array ?
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.
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.
Puneet kaushik said:
1 decade ago
Please explain this question in detail. I haven't understood yet.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers