10 Command Line Arguments 2015
10 Command Line Arguments 2015
where argc (argument count) is the number of command line arguments present on the command
line. argv (argument vector) is a pointer to an array of character strings. Therefore, argv[0] is a
pointer to the first command line string and argv[argc–1] is a pointer to the last command line string.
Example:
#include<stdio.h>
int main(int argc, char *argv[])
{ int i;
printf("My Executable File Name is %s\n",argv[0]);
for(i=1; i<argc; i++)
printf("Argument %d = %s\n", i, argv[i]);
return 0;
}
RUN:
./a.out I am Mr. K. Lakshmi Narayana you C Programming Instructor
Program1: Print the Sum of given Numbers by using Command Line Arguments
#include<stdio.h>
int main (int argc, char *argv[ ])
{ int j, sum=0;
for(j=1;j<argc;j++)
sum += atoi(argv[j]);
printf("SUM = %d",sum);
return 0;
}
RUN:
./a.out 10 25 55
SUM=90
By: K. L . Narayana 1
Command Line Arguments
Example:
#include<stdio.h>
int main (int argc, const char **argv)
{ int i;
double sum = 0;
for (i = 1; i < argc; i++)
sum += atof(*(argv+i));
printf("Sum=%d\n", sum);
return 0;
}
Program2: Read Full name from the user and print the First, middle and last names
#include<stdio.h>
int main(int argc, char *argv[])
{ int i;
if(argc==2)
printf("First Name :: %s\n", argv[1]);
else if(argc==3)
{
printf("First Name :: %s\n", argv[1]);
printf("Last Name :: %s\n", argv[2]);
}
else if(argc >3)
{
printf("First Name :: %s\n", argv[1]);
printf(“Middle Name ::");
for(i=2; i < argc-1; i++)
printf("%s ", argv[i]);
printf("\nLast Name :: %s\n", argv[argc-1]);
}
return 0;
}
RUN
./a.out Maharaj Shri Krushna Chandra Gajapati
First Name :: Maharaj
Middle Name :: Shri Krushna Chandra
Last Name :: Gajapati
By: K. L . Narayana 2