Find Maximum Number without using Conditional Statement or Ternary Operator

Given two numbers, calculate maximum number without using conditional statement or ternary operator.


 

Approach 1:

We can use (a > b)*b + (b > a)*a expression to find maximum number.

 
How this works?


Case 1: When a is greater

(a > b)*a + (b > a)*b = 1*a + 0*b = a

Case 2: When b is greater

(a > b)*a + (b > a)*b = 0*a + 1*b = b

C

Download   Run Code

 

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

We can take advantage of short-circuiting. In Boolean operation such as AND, y is evaluated only if x is true for x && y. y is not evaluated if x is false because the whole expression would be false which can be derived without evaluating y.

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 equal to a.

C

Download   Run Code

 

Approach 3: (Using array index)

We can also use array indices to find maximum number as shown below -

C

Download   Run Code

 

Approach 4: (Using repeated subtraction)

We can find maximum of two integers by doing repeated subtraction till both numbers becomes negative. The number of times we do subtraction will be the maximum number. This solution won't work on negative numbers.

C

Download   Run Code

Below is the recursive version of above solution but it uses conditional statement. Like iterative version, it won't work on negative numbers.

C

Download   Run Code

 
Also See: Find minimum number without using conditional statement or ternary operator

 
 
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