
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to demonstrate function of macros
Suppose we are given a integer array that contains several integer values. We have to find out the difference between the smallest value and the largest value in the array. To solve this problem, we have to use macros. The inputs are taken from stdin, and the result is printed back to stdout.
So, if the input is like array = {120, 589, 324, 221, 234}, then the output will be The answer is : 469
The difference between the largest value 589 and the smallest value 120 is 469.
To solve this, we will follow these steps −
- mini := infinity
- maxi := negative infinity
- for each i in v, do
- if mini > v[i], then
- mini := v[i]
- if maxi < v[i], then
- maxi := v[i]
- if mini > v[i], then
- ans := maxi - mini
- print(ans)
Example
Let us see the following implementation to get better understanding −
#define minmac(a, b) a = min(a, b) #define maxmac(a, b) a = max(a, b) #define INF ((1 << 31)-2) #define input(a) cin >> a #define toStr(a) string("The answer is :") #define FOO(a, b) #define foreach(a, b) for (int i = 0; i < a.size(); ++i) #include <iostream> #include <vector> using namespace std; FOO(minmac, <) FOO(maxmac, >) int main(){ int n; cin >> n; vector<int> v(n); foreach(v, i) { input(v)[i]; } int mini = INF; int maxi = -INF; foreach(v, i) { minmac(mini, v[i]); maxmac(maxi, v[i]); } int ans = maxi - mini; cout << toStr(The answer is :) <<' '<< ans; return 0; }
Input
5 120 589 324 221 234
Output
The answer is : 469
- Related Articles
- Golang program to demonstrate passing of pointers to a function
- C++ program to demonstrate exception handling
- C program to demonstrate usage of variable-length arrays
- C program to demonstrate fork() and pipe()
- C++ program to demonstrate multi-level inheritance
- C++ Program to Demonstrate the Implementation of 4-Color Problem
- Hygienic Macros in C
- Multiline macros in C
- Macros and Preprocessors in C
- Macros vs Functions in C
- Variable length arguments for Macros in C
- What are macros in C programming language?
- Golang Program to demonstrate the string concatenation
- Golang program to demonstrate the time arithmetic
- Golang program to demonstrate the string interpolation

Advertisements