Home » C Program for Arithmetic Expressions using Macros

C Program for Arithmetic Expressions using Macros

C macros are preprocessor directives like #define that is directly replaced into a source code in a C program. This replacement mechanism is called macro expansion.

In this example program, we will use a #define directive to do arithmetic operations.

Learn about C macro expansion before you begin with the example.

Problem Definition

As we mentioned earlier, #define directive is used to do macro expansion. In this program, we will write four function like macros that take two arguments and perform the arithmetic operations similar to a calculator.

For example, if X and Y are two arguments then

#define ADD(X, Y) ( X + Y)
#define SUBTRACT( X, Y) ( X - Y)
#define MULTIPLY(X, Y) (X * Y)
#define DIVIDE(X, Y) (X/Y)

Any variable that replaces X and Y will be used for arithmetic operations directly within the macros. Each opeation is separate and does not affect each other unless any expression changes the value of X or Y or both.

The source code of the program is given in the next section.

Program Source Code

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

#define ADD(X, Y) ( X + Y)
#define SUBTRACT(X, Y) (X - Y)
#define MULTIPLY(X, Y) (X * Y)
#define DIVIDE(X, Y) (X/Y)

int main()
{
int a,b; /* variable declaration and initialization */

int addition,subtraction,mul,division;

addition = subtraction = mul = division = 0;

/* Reading Input values */

printf("Enter two numbers:\n");
scanf("%d",&a); 
scanf("%d",&b);

/* Compute */

addition = ADD(a, b);
subtraction = SUBTRACT(a, b);
mul = MULTIPLY(a, b);
division = DIVIDE(a, b);

/* printing outputs */

printf("\n");
printf("_________________________\n");
printf("Addition = %d\n",addition);
printf("Subtraction = %d\n",subtraction);
printf("Multiplication = %d\n",mul);
printf("Division = %d\n",division);

getch();
system("PAUSE"); 
return 0;
}

Output

When the program executes, it asks for two input numbers – X and Y values. Once you enter the numbers, the preprocessor replaces the macros with actual codes and inputs are used to compute results.

The following screenshot shows the result obtained for inputs: X = 32 and Y = 2.

___________________________________
Enter two numbers:
34 2
___________________________________
Addition = 36
Subtraction = 32
Multiplication = 68
Division = 17

Related Articles:


(adsbygoogle = window.adsbygoogle || []).push({}); </script

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag

(adsbygoogle = window.adsbygoogle || []).push({});