# Write a c program to find max of 2 numbers

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

1 Like

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;
}
``````
2 Likes

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.

1 Like

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.

3 Likes

@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.

1 Like

â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.!

1 Like

can anyone tell me s for what? I can not understand. is it third number of three numbers? or it means any constant value? please explain

abs() is a function

#include<studio.h>
int main()
{
int a,b;
printf(âEnter two no.â);
scanf("%d %d",&a,&b);
if(a>b)
printf(âgreater is %dâ,a);
else
printf(âgreater is %dâ,b);
return 0;
}

1 Like

By considering cases a>b

and aâ¤b, itâs easy to see that

|aâb|=max(a,b)âmin(a,b),(note:|aâb|=|bâa|)

and

a+b=max(a,b)+min(a,b).
now put value of min(a,b) from above