Find maximum number without using conditional statement or ternary operator
Given two numbers, calculate the maximum number without using a conditional statement or ternary operator.
Approach 1
We can use (a > b) × b + (b > a) × a expression to find maximum number. This expression works as explained below.
(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
The following C program demonstrates it:
C
Approach 2: Using short-circuiting in Boolean expressions
We can take advantage of short-circuiting. 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.
The idea is to apply this principle to the following code. Initially, max is a. If max < b is true, then that means b is greater than a, so the second subexpression max = b is evaluated, and max is set to b. If, however, max < b is false, then the second subexpression will not be evaluated, and max 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 maximum(int a, int b) { // initialize `max` with `a` int max = a; // set `max` to `b` if and only if `max` is less than b` (max < b) && (max = b); return max; } int main() { printf("The maximum number is %d", maximum(9, 4)); return 0; } |
Approach 3: Using array index
We can also use array indices to find the maximum number, as shown below in C:
C
Approach 4: Using repeated subtraction
We can find the maximum of two integers by doing repeated subtraction till both numbers become negative. The total number of times we do removal will be the maximum number.
The implementation can be seen 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
Also See:
Find minimum 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 :)