Find minimum number without using conditional statement or ternary operator
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.
(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
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <stdio.h> 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); return min; } int main() { printf("The minimum number is %d", minimum(-8, 9)); return 0; } |
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
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
Approach 4: Using array index
We can cleverly use array indices to determine the minimum number, as shown below in C:
C
Also See:
Find maximum number without using conditional statement or ternary operator
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)