Given two integers, find the 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. This expression works as explained below.

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

The following C program demonstrates it:

C


Download  Run Code

Approach 2: Short–circuiting in Boolean expressions

We can take advantage of short-circuiting in Boolean expressions. In boolean operations 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 the above principle to the following code. Initially, min is a. Now if min > b is true, i.e., b is less than a, the second subexpression min = b will be evaluated and min will set to b; otherwise, if min > b is false, the second subexpression will not be evaluated and min will remain equal to a.

C


Download  Run Code

Approach 3: Using repeated subtraction

We can find the minimum of two integers by doing repeated subtraction until any number becomes zero. The total number of times we do removal will be the minimum number.

This approach is demonstrated below in C. This solution won’t work on negative numbers.

C


Download  Run Code

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

C


Download  Run Code

Approach 4: Using array index

We can cleverly use array indices to determine the minimum number, as shown below in C:

C


Download  Run Code

 
Also See:

Find maximum number without using conditional statement or ternary operator