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.

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

The following C program demonstrates it:

C


Download  Run Code

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


Download  Run Code

Approach 3: Using array index

We can also use array indices to find the maximum number, as shown below in C:

C


Download  Run Code

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


Download  Run Code

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


Download  Run Code

 
Also See:

Find minimum number without using conditional statement or ternary operator