Ujjwal Bhardwaj
Ujjwal Bhardwaj

Reputation: 19

how to find which integer no is maximim out of given numbers

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x, y, z, result, max;
    printf("\nInput the first integer: "); 
    scanf("%d", &x);
    printf("\nInput the second integer: ");
    scanf("%d", &y);
    printf("\nInput the third integer: ");
    scanf("%d", &z);
    result=(x+y+abs(x-y))/2;
    max=(result+z+abs(result-z))/2;
    printf("\nMaximum value of three integers: %d", max);
    printf("\n");
    return 0;
}

unable to understand the formula:

result=(x+y+abs(x-y))/2;
max=(result+z+abs(result-z))/2;

Upvotes: 1

Views: 98

Answers (4)

nonopolarity
nonopolarity

Reputation: 151026

One way to visualize it is:

Imagine you have 2 trees. One is 16 meter tall and the other is 20 meter tall.

You look at their average, which is the “midpoint” and is 18 meter tall. Now, what’s their difference? 4 meter.

You take 18 and add half of that difference, is 20 (the max). Likewise, you can take the average and minus half of the difference and it is the min.

So,

  average plus half the difference
= (x + y) / 2 + abs(x - y) / 2
= (x + y + abs(x - y)) / 2

Upvotes: 1

dbush
dbush

Reputation: 223917

Looking at this expression:

(x+y+abs(x-y))/2

If x => y, then abs(x-y) is the same as x-y. That gives us: (x+y+(x-y))/2 == (x+x+y-y)/2 == 2x/2 == x.

If x < y, then abs(x-y) is the same as y-x. That gives us: (x+y+(y-x))/2 == (x-x+y+y)/2 == 2y/2 == y.

So the above expression evaluates to the larger of x and y without using any conditionals. The following expression (result+z+abs(result-z))/2 does the same thing with z and the max of x and y.

Note however that this method has the potential to cause overflow. The cleanest way to do this is to explicitly compare:

if (x >= y && x >= z) {
    max = x;
} else if (y >= x && y >= z) {
    max = y;
} else  {
    max = z;
}

Upvotes: 2

Jim Rhodes
Jim Rhodes

Reputation: 5085

The following line of code returns the value of whichever is greater, x or y.

result = (x + y + abs(x - y)) / 2;

By adding the absolute value of the difference between x and yto the sum of x and y you essentially get 2 times the larger number. For example, if x=5 and y=20 then abs(x - y) = 15. So 5 + 20 + 15 = 40 which is 2 times the larger number. Divide that by 2 and you have determined larger value. Then by repeating the formula with the result above and z you have calculated the largest of the three.

Upvotes: 0

0___________
0___________

Reputation: 67536

then how to solveit – Ujjwal Bhardwaj 5 mins ago

int max(int a, int b, int c)
{
    return a > b ? (a > c ? a : c) : (b > c ? b : c);
}

Upvotes: 1

Related Questions