Groovy hepcat Larry Tooley was jivin' on Sun, 28 Jan 2007 01:31:37
-0500 in comp.lang.c.
Newbie Problem's a cool scene! Dig it!
I am new to C and am using "C How to Program" to get started with my C
education. I am working an exercise where I am supposed to use only
arithmetic, equity and relational operators, and the "if" statement to
determine the largest and smallest of three integers. It seems like there
is an easy answer, but I just haven't come up with a solution. It has
been a long time since CS101 with Pascal so pardon my ignorance.
Divide and conquer. That's the first principle of programming. Break
a large problem down into a smaller one. You determine the largest of
three numbers by first finding the largest of two of them, then
finding the largest of the result of that operation and the last
number. We'll express the largest of two values as MAX(x,y) where x
and y represent the two values.
So, say you have numbers labelled a, b and c. To find the largest of
these three, you first find MAX(a,b). Then you find MAX(MAX(a,b),c).
In fact, C's syntax makes it easy to do that in one go. All you need
is a function that can return the larger of two values. This, of
course, is trivial.
int max(int x, int y)
{
if(x >= y)
{
return x;
}
else
{
return y;
}
}
#include <stdio.h>
int main(void)
{
int a = 107, b = 42, c = 23;
int big = max(max(a, b), c);
printf("The biggest of %d, %d and %d is %d.\n", a, b, c, big);
return 0;
}
The above code is quite self explanitory. Notice the use of the max()
function. If max(a, b) returns the largest of a and b, then max(max(a,
b), c) returns the largest of (the largest of a and b) and c; which,
of course, gives us the largest of the three numbers. What could be
simpler?
--
Dig the even newer still, yet more improved, sig!
http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?