Find maximum, minimum of three numbers without using conditional statement and ternary operator | 4 methods

Given three integers, find maximum and minimum number between them without using conditional statement or ternary operator.


 


 
Approach 1: (Using short-circuiting in Boolean expressions)

The idea is to take advantage of short-circuiting in Boolean expressions. We know that in Boolean AND operation such as x && y, y is evaluated only if x is true. If x is false, then y is not evaluated, because the whole expression would be false which can be deduced without even evaluating y. This is called short-circuiting in Boolean expressions.

The idea is to apply this principle to the below code. Initially max is a. Now if (max < b) is true, then that means, b is greater than a so the second sub-expression (max = b) is evaluated and max is set to b. If however (max < b) is false, then second sub-expression will not be evaluated and max will remain a (which is greater than b). In a similar fashion, the second expression is evaluated. We can implement minimum function as well in similar fashion.  
 

Download   Run Code

 
Approach 2: (Using array index)
 

Download   Run Code

 
Approach 3: (Approach 2 Simplified)

We can simplify approach 2 by breaking the problem into finding maximum/minimum of two numbers.

 

Download   Run Code

We can implement minimum function as well in similar fashion.

 

Download   Run Code

 
Approach 4: (Using repeated subtraction)

 

Download   Run Code

 

References:
http://stackoverflow.com/questions/7074010/find-maximum-of-three-number-in-c-without-using-conditional-statement-and-ternar

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz