A C program that uses macros, MIN & MAX, to find and return, respectively the minimum & maximum of two values

By | August 27, 2013

Macro are the small code which is substituted wherever the macro is refered. macros can be used in two ways :

First way as a replacement to the code which is long in length or repeated all the time.  e.g. #define CUBE(X) (X*X*X)

Second way as a small function in which we can pass arguments and return results. In this method, we have to use Ternary operator. e.g. #define ABSOLUTE(NUM)  ((NUM) < 0) ? -(NUM) : (NUM)

Ternary operator is a conditional operator (?:) which is related to the if-else structure.
syntax looks like this :
(condition)? (expression1): (expression2);

First part is a conditional expression. Second part represents the value to be evaluated if condition is true. Third part is represents the value to be evaluated if condition is false.

Let’s write Macro for Minimum (MIN) and maximum (MAX).

#define MIN(X,Y) (X<Y ? X:Y)
#define MAX(X,Y) (X>Y ? X:Y)

Here we are passing two arguments to Macro (i.e. X & Y) and checking condition if X is less than Y and if the condition is True than the X variable is returned (This placed can be written by any Expression to be evaluated or a simple variable also.)  and if the condition is False than the Y variable is returned.

Now, let’s find varibles needed

Since we are going to use the above macro as a function call, hence we will need two variables i.e. FIRST and SECOND.

Data type will be int (integer) data type as numbers will be entered by user and check the min value and the max value.

Enter message for user to enter values, scan the values and save it in respective variables. Call the macro similar to function call and the value will be returned to the calling position. print the values done.

C program code:

#include<stdio.h>
 
#define MIN(X,Y)(X<Y ? X:Y)
#define MAX(X,Y)(X>Y ? X:Y)
 
void main()
{
    int FIRST,SECOND;
    clrscr();
    printf("ENTER NUMBERS TO COMPARE\n");
    printf("\nFIRST NUMBER : ");
    scanf("%d", &FIRST);
    printf("\nSECOND NUMBER : ");
    scanf("%d", &SECOND);
    printf("\nTHE LARGER NUMBER IS %d", MAX(FIRST,SECOND));
    printf("\nThe SMALLER NUMBER IS %d", MIN(FIRST,SECOND));
    getch();
}

Screen Shots:-

C_program_Ternary_Min_Max

C_program_Ternary_Min_Max_Output

Leave a Reply