 # 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