Maximum of four numbers without using conditional or bitwise operator in C++

C++Server Side ProgrammingProgramming

In this problem, we are given four integer numbers. Our task is to create a program to find the maximum of four numbers without using conditional or bitwise operator in C++.

Code Description − Here, we have four integer values. And we need to find the maximum value out of these numbers without using any conditional or bitwise operator.

Let’s take an example to understand the problem,

Input

a = 4, b = 7, c = 1, d = 9

Output

9

Solution Approach

To solve the problem, we will take two elements first, then take the greater element with pair. For each pair, we will create a 2 element arr[] and find which element is greater using the boolean value. The boolean value is used as index, found using the the formula [abs(x - y) + (x - y)].

An easy explanation is,

If arr[0] is greater than arr[1], boolean value is False. else it is True.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findMax(int x, int y){
   int arr[2] = {x,y};
   bool MaxIndex = ( !(arr[0] - arr[1] + abs(arr[0] - arr[1])));
   return arr[MaxIndex];
}
int CalcMaxElement(int a, int b, int c, int d) {
   int max = a;
   max = findMax(max, b);
   max = findMax(max, c);
   max = findMax(max, d);
   return max;
}
int main() {
   int a = 4, b = 9, c = 7, d = 1;
   cout<<"The maximum of four numbers is "<<CalcMaxElement(a,b,c,d);
   return 0;
}

Output

The maximum of four numbers is 9
raja
Published on 08-Jun-2020 10:41:00
Advertisements