« Previous                                                                 Next Chapter » 
Command Line Arguments

We can pass arguments to C programs when they are executed. The brackets which follow main are used for this purpose. argc refers to the number of arguments passed, and argv[ ] is a pointer array which points to each argument which is passed to main.

More Examples
/* main as without parameter,without return value */
#include<stdio.h>
#include<conio.h>
void main(void)
{
printf("ding");
}

/* main as without parameter,with return value */
#include<stdio.h>
#include<conio.h>
char main(void)
{
printf("ding");
return 'x';
}

/* default main return type is integer */
#include<stdio.h>
#include<conio.h>
main(void)
{
printf("ding");
return 23;
}

/* program to find argc,argv */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
clrscr();
printf("the total no of args are %d\n",argc);
printf("the name of the programe is %s\n",argv[0]);
return 5;
}

/* program to read commandline arguments */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
clrscr();
printf("the total no of args are %d\n",argc);
printf("the name of the programe is %s\n",argv[0]);
printf("the first arg is %s\n",argv[1]);
printf("the second arg is %s\n",argv[2]);
printf("the third arg is %s\n",argv[3]);
printf("the fourth arg is %s\n",argv[4]);
}

/* program to addition of two numbers by commandline arguments */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
int a,b,c;
clrscr();
printf("the total no of args are %d\n",argc);
printf("the name of the prog is %s\n",argv[0]);
a=atoi(argv[1]);
b=atoi(argv[2]);
c=a+b;
printf("the sum is %d\n",c);
}

/* program to find simple interest by commandline arguments */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
int p,n,r;
float si;
clrscr();
printf("the total no of args are %d\n",argc);
printf("the name of the prog is %s\n",argv[0]);
p=atoi(argv[1]);
n=atoi(argv[2]);
r=atoi(argv[3]);
si=(float)(p*n*r)/100;
printf("the simple interest is %f\n",si);
}

/* program on arrays by commandline arguments */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
int a[10],n,i;
clrscr();
printf("the total no of args are %d\n",argc);
printf("the name of the prog is %s\n",argv[0]);
n=atoi(argv[1]);
for(i=0;i<n;i++)
{
a[i]=atoi(argv[i+2]);
}
  printf("the values are \n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
}



  « Previous                                                                 Next Chapter »