C++ program to demonstrate function of macros

C++Server Side ProgrammingProgramming

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]
  • 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
raja
Published on 12-Oct-2021 06:35:01
Advertisements