write a c program to find max of two number and number taken from user

you can use only operators +,-,abs,division and number should be integer

it’s easy. the max between A and B can be considered as the value

located at |A-B|/2 distance from the middle (A+B)/2, to the right.

thus, the formula is : (A+B+abs(A-B))/2. you only use +, -, abs and

division. it only works for non-negative integers, obviously.

```
int max(int A, int B)
{
return (A + B + abs(A - B)) / 2;
}
```

the formula is perfect…!!

But can you just explain it in another simpler way…I am sort of not getting how that formula was derived.

Let B be the max.

|A-B|/2 | |-----------| v v ----------- A ---------------------- B -------------- ^ | (A+B)/2

As you can see, the formula is reversible, meaning if A is the max, the expression remains :

* (A+B) / 2 = (B+A) / 2 * |A-B| / 2 = |B-A| / 2

Thus, max(A, B) = middle_position + gap_between_both / 2

= (A+B) / 2 + |A-B| / 2

= (A + B + abs(A - B)) / 2

Hope this helps.

@cool_techie It is pretty simple to understand. It follows from the definition of abs.

```
if A=B
abs(A-B) = 0
A+B+abs(A-B) = 2A
if A>B
abs(A-B) = A-B
A+B+abs(A-B) = 2A
if B>A
abs(A-B) = B-A
A+B+abs(A-B) = 2B
```

This is not dependent on the sign of the numbers as @cyberax pointed out. But yes it has troubles with overflow and underflow.

“This is not dependent on the sign of the numbers as @cyberax pointed out.”

true ! my bad. i was tired

Thanks, it helped me to understand the concept.!