C Programming - Command Line Arguments - Discussion

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

int main(int argc, char **argv)
{
    int i, j=0;
    for(i=0; i<argc; i++)
        j = j+atoi(argv[i]);
    printf("%d\n", j);
    return 0;
}
123
6
Error
"123"
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
15 comments Page 1 of 2.

Andrew said:   2 decades ago
The answer given is incorrect. argv[0] is normally the filename of the program being called. The list of argumnets would be myprog.exe 1 2 3 Therefore atoi(argv[0]) does not return what you expect 1.

Sundar said:   2 decades ago
Hi Andrew,

As you said, argv[0] always contains the filename of the program being called.

But atoi() converts "myprog.exe" (string) into 0(integer zero).

So, 0 + 1 + 2 + 3 = 6.

Therefore it will print 6 as output.

Note:
=====

1. atoi("123Sundar.exe") will return 123.

2. atoi("sundar.exe") will return 0.

3. While calling the above program (exe) from command prompt like "C:\Turboc>myprog 1 2 3", the argv[0] will contain "C:\TURBOC\MYPROG.EXE".

While converting the value with atoi("C:\TURBOC\MYPROG.EXE"), it returns 0 (zero).

Sandiya said:   1 decade ago
Thank you Sundar. Nice explanation.

Marichamy said:   1 decade ago
Good explanation Sundar.

Ayush said:   1 decade ago
Hii sundar I cannot understand how the command line arguments are assigned to variable argc and argo please explain the whole process.

Sreenivas said:   1 decade ago
Sunder your explanation was awesome.

Vanaraju said:   1 decade ago
I didn't understand please give me another explanation.

Apurva Nigam said:   1 decade ago
Really helpful explanation @Sundar.

Thanks.

Rajesh said:   1 decade ago
Nice explanation sundar.

Sunitha said:   1 decade ago
argc will take the no of command line arguments,

i.e. If "myprog one two three" then argc=4 and argv is a array of that command line arugemnt ie argv[0] means myprog,argv[1] means one like that.


Post your comments here:

Your comments will be displayed after verification.