Array MinMax Function Problem

I have the question:
Write the definition of a function max that has three int parameters and returns the largest.


My attempt is does not work properly can anyone tell me why?

int max(int a, int b, int c)
{
if (num1 > num2 && num1 > num3)
{
return num1;
}
else if (num2 > num1 && num2 > num3)
{
return num2;
}
else if (num3 > num1 && num3 > num2)
{
return num3;
}
}
You are passing 3 parameters (a, b, and c), but you are checking for variables called num1, num2, and num3.
Challenge:

rewrite the above code to use only 3 boolean tests instead of 6.
Isn't this really 9 Boolean tests? Since the '&&' operator is 'a*b=true\false'? :p Not trying to one up you just pointing out that this is even more inefficent then previously thought.
I'm not sure if j's challenge was meant for all of us beginners, but I decided to give it a shot:

1
2
3
4
5
6
int GetLargest(int a, int b, int c)
{
	return (a>b) ?	// Is a greater than b?
		((a>c) ? a : c)	// Yes - but is a > c? If yes, return a, otherwise return c.
		: ((b>c) ? b : c); // No - hence b>=a. Is b > c? If yes, return b, otherwise return c.
}


3 boolean tests here, right?
Maybe less?

1
2
3
4
5
6
7
8
9
10
11
if (a>b)
{
     if (a>c)
     { return a;}
                       }

if (b>c)
{return b;}

else
{return c;}


Yes technically there are three boolean operators, but your system only ever runs two comparisons before assuming that 'c' is the largest variable.

EDIT: Never mind this is what sammy34 did but he didn't point out that the system only runs to comparisons so I had to *ugh* read the code to see it :p.
Last edited on
Bingo.

My way was:
1
2
3
4
5
6
7
    if( a > b && a > c )
        return a;

    if( b > c )
        return b;

    return c;


(Though Computergeek01, it will run all three if c > a > b.)

And you can one-liner it:

 
    return std::max( a, std::max( b, c ) );


This actually runs only 2 checks.
Topic archived. No new replies allowed.