Step 2 of 7
Write a function
Now write a whole function yourself. The task is to return the largest of three numbers. Before typing any code, think through the logic the way you'd do it by hand.
Step 1: solve the smaller problem
Finding the larger of two numbers is easy:
int max2(int a, int b) {
if (a > b) {
return a;
}
return b;
}
Notice there's no else: return ends the function immediately, so if a > b the second return is never reached. Many programmers like this "return early" style.
Step 2: build on it
For three numbers you can keep a "best so far" variable, the same idea as finding a maximum in a loop:
#include <stdio.h>
int min3(int a, int b, int c) {
int best = a;
if (b < best) {
best = b;
}
if (c < best) {
best = c;
}
return best;
}
int main(void) {
printf("%d %d %d\n", min3(5, 2, 9), min3(1, 1, 1), min3(-4, 0, -7));
return 0;
}
2 1 -7
That's the minimum; the maximum is the same idea with the comparisons flipped.
Think about edge cases
Hidden tests will try tricky inputs, so ask yourself: what if two numbers are equal? What if all are negative? What if the largest is first, or last? The "best so far" approach handles all of those without special cases, which is a sign it's a good approach.
Every path must return
If a function promises to return an int, every way through it must reach a return. If one path falls off the end without returning, the caller gets garbage (formally, undefined behavior); the compiler warns non-void function does not return a value in all control paths.
Your task
Write int max3(int a, int b, int c) that returns the largest of three numbers.
Challenge 2
Write int clamp(int x, int lo, int hi) that returns x if it is between lo and hi, lo if x is smaller than that, and hi if it is bigger. Games use this to keep values like HP inside a range.
Challenge 3
Write int median3(int a, int b, int c) that returns the middle value of the three: the one that is neither the smallest nor the largest. median3(9, 2, 5) returns 5. Equal values count too, so median3(4, 4, 1) returns 4.