The task for this month’s Exercise is to write a function, greatest(), that returns the largest of three values. While this task could be done easily with an if-else construction, the second part of the challenge is to write the entire thing as a single ternary statement. How’d you do?
Starting with the easy way, here is my first solution:
2025_12-Exercise-a.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int greatest(int a, int b, int c)
{
int max;
max = a;
if( b>max )
max = b;
if( c>max )
max = c;
return(max);
}
int main()
{
int x,y,z,g;
/* seed the randomizer */
srand( (unsigned)time(NULL) );
/* generate three random values from 2 to 25 */
x = rand() % 24 + 2;
y = rand() % 24 + 2;
z = rand() % 24 + 2;
g = greatest(x,y,z);
printf("The greatest of %d, %d, and %d is %d\n",
x,y,z,g
);
return 0;
}
The main() function generates the three random values, x, y, and z, in the range of 2 to 25. These values are passed to the greatest() function, which returns the largest value. The results are output.
In the greatest() function, argument a is assigned as the greatest value, stored in variable max: max = a This assignment is followed by two comparisons: if variable b is greater than max, max is assigned its value. Should variable c be greater than max, max is assigned its value. Finally, the value of max is returned.
Here are several sample runs of this solution:
The greatest of 11, 6, and 5 is 11
The greatest of 4, 11, and 25 is 25
The greatest of 24, 9, and 12 is 24
The greatest of 3, 17, and 12 is 17
The greatest of 18, 11, and 24 is 24
The second solution — if you dared attempt it — uses the ternary operator in a single statement to obtain the maximum value of the three arguments passed. This solution requires updating the greatest() function to include only the following statement:
return( b>a ? b>c ? b : c : a>c ? a : c );
Marvel at the obfuscation! The code works, and it took me a while to construct it properly. In fact, I admire it even more when I remove the whitespace:
return( b>a?b>c?b:c:a>c?a:c );
To unwind this expression, start at the right end, which I’m color-coding here:
return( b>a ? b>c ? b : c : a>c ? a : c );
The result of this operation is argument a or c, whichever is greater.
Next, hop to the second part of the expression:
return( b>a ? b>c ? b : c : a>c ? a : c );
The result of this expression is either argument b or c, whichever is greater.
At this point, both arguments a and b have been compared with argument c. What remains is for them to be compared with each other, which is the first part of the expression: b>a. So, if b is greater than a and b is greater than c, b is returned. Otherwise, if a is greater than b and a is greater than c, it’s returned. Otherwise, c is returned.
What a mess! Nested ternary statements are insane! But the thing works.
Click here to view my second solution in its entirety on GitHub.
I hope that your solutions met with success!