Ad Code

Responsive Advertisement

command line argument

Command Line Arguments

It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
There are two arguments are define in to main() function.

-> argc refers to the number of arguments passed.
-> argv[] is a pointer array which points to each argument passed to the program.

Example
#include <stdio.h>
#include <conio.h>
int main(int args,char *argv[])
{
 int i;
 for(i=0;i<args;i++)
 {
      printf("%s\n",argv[i]);
 }
 return(0);
}

for Ubuntu :

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

void main (int argc, char * argv[])
{
   system("clear") ;  // clrscr() ;
   printf("%s", argv[1]);
}

output : hello


WAP to find bigger no from given two number. 

#include<stdlib.h>
int main(int argc, char * argv[] )
{
 int a,b;
 if(argc!=3)
 {
 printf("you have to specify two argumments only...");
 exit(1);
 }
 a=atoi(argv[1]); //assuming the argument value is a character
 b=atoi(argv[2]);
 if(a>b)
 printf("a is bigger");
 else
 printf("b is bigger");
 return 0;
}

 for ubuntu

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

void main (int argc, char * argv[])
{
   system("clear") ;  // clrscr() ;
   int a, b;
   a=atoi(argv[1];
   b=atoi(argv[2]);

   if(a>b)
   {
       printf(" a is greater ") ;
   }
   else
    {
       printf("  b is greater ") ;
    }
}
out put : 12 20
           b is greater.



WAP To check the number is odd or even

#include<stdlib.h>
int main(int argc, char * argv[] )
{
 int a;
 if (argc != 2)
 {
printf("You have to specify a single integer as argument.");
 exit(1);
 }
 a=atoi(argv[1]); //assuming the argument value is a character
 if((a%2)==0)
 printf("%d is a even number",a);
 else
 printf("%s is a odd number",argv[1]);
 return 0;
}

Example Addition of numbers with command line arguments

#include<stdio.h>
 int main(int argc, char *argv[])
{
 int i, sum = 0;
 printf("The sum is : ");
 for (i = 0; i < argc; i++) {
 sum = sum + atoi( argv[i] );

 // 'atoi()' used to convert alphabet to integer.
 }
 printf("%d", sum);
 return 0;
}

Post a Comment

0 Comments