Given two integers, find minimum number between them without using any conditional statement (or ternary operator).
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
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.
int minimum(int a, int b)
// initialize min with a
int min = a;
// set min to b if and only if min is more than b
(min > b) && (min = b);
// main function
printf("Minimum number is %d", minimum(-8, 9));
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.
Below is the recursive version of above solution but it uses conditional statement. Like iterative version, it won’t work on negative numbers.
Approach 4: (Using array index)
We can cleverly use array indices to determine minimum number as shown below –
Thanks for reading.