Given two numbers, calculate maximum number without using conditional statement or ternary operator.
Approach 1:
We can use (a > b)*b + (b > a)*a
expression to find maximum number.
How this works?
Case 1: When a is greater
(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
C
Approach 2: (Using short-circuiting in Boolean expressions)
We can take advantage of short-circuiting. 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.
The idea is to apply this principle to the below code. Initially max is a. Now if (max < b)
is true, then that means, b is greater than a so the second sub-expression (max = b)
is evaluated and max is set to b. If however (max < b)
is false, then second sub-expression 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 20 |
#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; } // main function int main() { printf("Maximum number is %d", maximum(9, 4)); return 0; } |
Approach 3: (Using array index)
We can also use array indices to find maximum number as shown below -
C
Approach 4: (Using repeated subtraction)
We can find maximum of two integers by doing repeated subtraction till both numbers becomes negative. The number of times we do subtraction will be the maximum number. This solution won't work on negative numbers.
C
Below is the recursive version of above solution but it uses conditional statement. Like 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.
Please use our C Shell 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