Find Minimum Number without using Conditional Statement or Ternary Operator

Given two integers, find minimum number between them without using any conditional statement (or ternary operator).


Approach 1:

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

How this works?

Case 1: When a is greater

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

Case 2: When b is greater

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


Download   Run Code


Approach 2: (Short-circuiting in Boolean expressions)

We can take advantage of short-circuiting in Boolean expressions. 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.

We can apply above principle to the below code. Initially min is a. Now if (min > b) is true i.e. b is less than a, the second sub-expression (min = b) will be evaluated & min will set to b else if (min > b) is false, second sub-expression will not be evaluated and min will remain equal to a.


Download   Run Code


Approach 3: (Using repeated subtraction)

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


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.


Download   Run Code


Approach 4: (Using array index)

We can cleverly use array indices to determine minimum number as shown below –


Download   Run Code

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

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of