How to Run Command Line Arguments in C Program Example with Explanations


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main(int argc,char *argv[])
{
int sum=0,i;
//Compare if proper number of arguments have been entered
if(argc<3)
{
printf("Insufficient number of arguments:\n");
getch();
return 0;
}

//Add all the numbers entered using atoi function, ie default String, to be converted as integer
for(i=1;i<argc;i++)
{
sum+=atoi(argv[i]);
}

//printing the sum
printf("Sum of entered Numbers=%d",sum);
getch();
}

/* Just Compile and Run, then you will get "Insufficient number of arguments" message and press enter key.
 then you will go to File menu and click Dos shell option, then you will get a prompt like C:\TC\BIN.
there you type C:\TC\BIN\filename "12" "13" press enter key. Answer will be Sum of entered numbers=25
 ie "12" and "13" are arguments which are given as Command Line Arguments  */