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
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;
}
Discussion:
15 comments Page 2 of 2.
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.
Marichamy said:
1 decade ago
Good explanation Sundar.
Sandiya said:
1 decade ago
Thank you Sundar. Nice explanation.
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).
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).
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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers