C program to find maximum or minimum using macro

Write a C program to find maximum and minimum of two numbers using macro. How to find maximum or minimum between two numbers using macro in C program. Logic to find maximum and minimum using macro in C.

In last post we learned adding conditions to our macro. We learned to check even or odd number using macro

In this post we will continue the exercise further. I will explain how easily you can transform our maximum or minimum check function to macro.

Required knowledge

Basic C programming, Macros, Conditional operator

There are several ways to check maximum or minimum between two numbers. In case you missed I have listed down the links below.

How to find maximum or minimum using macro?

I assume that you are already aware with macro syntax, how to define and use. Hence, without wasting much time let us get started.

Lets define two macro that accepts two arguments say MAX(x, y) and MIN(x, y). It will return maximum or minimum number respectively. For this exercise we will use conditional (ternary) operator to find maximum or minimum.

Example:

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

Program to find maximum or minimum using macro

/**
 * C program to check maximum/minimum using macro
 */

#include <stdio.h>

// Define macro to check maximum and minimum
#define MAX(x, y) (x > y ? x : y)
#define MIN(x, y) (x < y ? x : y)

int main()
{
    int num1, num2;

    // Input numbers from user
    printf("Enter any two number to check max and min: ");
    scanf("%d%d", &num1, &num2);

    printf("MAX(%d, %d) = %d\n", num1, num2, MAX(num1, num2));
    printf("MIN(%d, %d) = %d\n", num1, num2, MIN(num1, num2));

    return 0;
}

Output

Enter any two number to check max and min: 10 20
MAX(10, 20) = 20
MIN(10, 20) = 10

Happy coding 😉