Friday, May 13, 2022

Assignment 7: Command line arguments and preprocessor directives

 Assignment 7: Command line arguments and preprocessor directives


If any input value (or commands)is passed through the command prompt at the time of running of program is known as command line argument. It is a concept to passing the arguments to the main() function by using command prompt. 

Preprocessor directives are lines included in a program that being with the character #, which make them different from a typical source code text. They are invoked by the compiler to process some programs before compilation.

main() function of a C program accepts arguments from command line or from other shell scripts by

using the concept of command–line arguments.

Syntax: int main( int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which

holds pointers of type char which points to the arguments passed to the program.

In real time application, it will happen to pass arguments to the main program itself. These arguments

are passed to the main () function while executing binary file from command line.

When Use Command Line Argument :-

When you need to developing an application for DOS operating system then in that case command line

arguments are used. DOS operating system is a command interface operating system so by using

command we execute the program. With the help of command line arguments we can create our own

commands.

Example:-

#include <stdio.h>  

void main(int argc, char *argv[] )  {  

     printf("Program name is: %s\n", argv[0]);  

      if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  


Run this program as follows in Linux:

./program hello 

Output:-

Program name is: program

First argument is: hello


Preprocessor directives

 Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called preprocessing.

 Commands used in preprocessor are called preprocessor directives and they begin with “#”  symbol.


Below is the list of preprocessor directives that C programming language offers.

Preprocessor Syntax/Description

1)Macro

Syntax: #define

This macro defines constant value and can be any of the basic data types.

2) Header file inclusion

Syntax: #include <file_name>

The source code of the file “file_name” is included in the main program at the 

specified place.

3) Conditional compilation

Syntax: #ifdef, #endif, #if, #else, #ifndef

Set of commands are included or excluded in source program before compilation with respect to the condition.

4) Other directives

Syntax: #undef, #pragma

#undef is used to undefine a defined macro variable.

 #Pragma is used to call a function before and after main function in a C program.


Sample Program 1)

#define INRANGE(m) ( m>= 1 && m<=12) 

#define NEGATIVE(m)(m<0)

#define ISLOWER(c) (c>=’a’&&c<=’z’) 

#define ISUPPER(c) (c>=’A’&&c<=’Z’)

#define ISALPHA(c) (ISUPPER(c)||ISLOWER(c))

#define ISDIGIT(c)(c>=’0’&&c<=’9’)

void main()

{

int m; char c;

printf(“Enter an integer corresponding to the month”); 

scanf(“%d”,&m);

if(NEGATIVE(m))

printf(“Enter a positive number”); 

else

if(INRANGE(m))

printf(“You Entered a valid month”);

printf(“Enter a character:”); 

c=getchar(); 

if(ISAPLHA(c))

printf(“You entered an alphabet”); 

else

if(ISDIGIT(c))

printf(“You Entered a digit”);

}


1. Write a program to define value of pi and use it to find area and perimeter of a circle.

#include <stdio.h>

 #define PI 3.14f

 int main()

{

    float rad,area, perm;

     printf("Enter radius of circle: ");

    scanf("%f",&rad);

    area=PI*rad*rad;

    perm=2*PI*rad;

     printf("Area of circle: %f \nPerimeter of circle: %f\n",area,perm);

    return 0;

}


2. Write a program to display all command line arguments passed to main in the reverse order. 

#include<stdio.h>

#include<stdlib.h>

int main(int argc,char * argv[])

{

int i;

for(i=argc-1;i>0;i--)

  printf("\n Argument [%d] is : %s",i,argv[i]);

return 0;

}


3. Write a program to accept three integers as command line arguments and find the minimum, maximum and average of the three. Display error message if invalid number of arguments are entered.

#include<stdio.h>

void main(int argc , char * argv[])

{

            int i,sum=0;

            float avg;

            int max;

            int min;

            if(argc!=4)

              {

              printf("you have forgot to type numbers.");

              exit(1);

              } 

            for(i=1;i<argc;i++)

             {        sum = sum + atoi(argv[i]);

                        avg=sum/3;

                        }

             printf("the average is%f",avg);

             //for max

             max=argv[1];

             min=argv[1];

                        for(i=1;i<argc;i++)

                          {

                        if(atoi(argv[i])>max)

                         {

                         max=atoi(argv[i]);

                         }

                         }

                            if(atoi(argv[i])<min)

                         {

                         min=atoi(argv[i]);

                         }

  printf("\n the maximum number is %d",max);

              printf("\n the minimum number is %d",min);   

}

4. Define a macro MIN which gives the minimum of two numbers. Use this macro to find the minimum of n numbers.

#include <stdio.h>

#define MIN(x,y) ((x<y)?x:y)

int main()

{

int a,b,min;

printf("Enter first number: ");

scanf("%d",&a);

printf("Enter second number: ");

scanf("%d",&b);

min=MIN(a,b);

printf("Minimum number is: %d\n",min);

return 0;

}


Set A . Write C programs for the following problems.

1. Write a program to accept three integers as command line arguments and find the minimum, maximum and average of the three. Display error message if invalid number of arguments are entered.

 

#include<stdio.h>

 

void main(int argc , char * argv[])

{

            int i,sum=0;

            float avg;

            int max;

            int min;

            clrscr();

 

            if(argc!=4)

              {

              printf("you have forgot to type numbers.");

              exit(1);

              }

            for(i=1;i<argc;i++)

             {

                        sum = sum + atoi(argv[i]);

                        avg=sum/3;

                        }

             printf("the average is%f",avg);

 

             //for max

             max=argv[1];

             min=argv[1];

                        for(i=1;i<argc;i++)

                          {

                        if(atoi(argv[i])>max)

                         {

                         max=atoi(argv[i]);

                         }

                         }

                            if(atoi(argv[i])<min)

                         {

                         min=atoi(argv[i]);

                         }

  printf("\n the maximum number is %d",max);

              printf("\n the minimum number is %d",min);

                         

}

 

2. Write a program which accepts a string and two characters as command line arguments and replace all occurrences of the first character by the second.

#include <stdio.h>

#include <string.h>

#include<ctype.h>

int main(int argc, char *argv[])

{

   char str[100], ch, Newch;

   int i;

   

   strcpy(str,argv[1]);

       

   for(i = 0; i <= strlen(str); i++)

   {

   if(str[i] == argv[2][0])  

{

   str[i] = argv[3][0];

  }

}

printf("\n The Final String after Replacing All Occurrences of '%s' with '%s' = %s ", argv[2], argv[3], str);

   return 0;

}

 


3. Define a macro MAX which gives the maximum of two numbers. Use this macro to find the maximum of n numbers.

 

#include <stdio.h>

#define MAX(x,y) ((x>y)?x:y)

int main()

{

int a,b,min;

printf("Enter first number: ");

scanf("%d",&a);

printf("Enter second number: ");

scanf("%d",&b);

min=MAX(a,b);

printf("Maximum number is: %d\n",min);

return 0;

}

No comments:

Post a Comment