Given two numbers, calculate maximum number without using conditional statement or ternary operator.
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
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.
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);
// main function
printf("Maximum number is %d", maximum(9, 4));
Approach 3: (Using array index)
We can also use array indices to find maximum number as shown below -
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.
Below is the recursive version of above solution but it uses conditional statement. Like iterative version, it won't work on negative numbers.
Thanks for reading.
Please use our C Shell to post code in comments.
Like us? Please spread the word and help us grow. Happy coding :)