Challenge: Clamp with Macros
Completed
Write two macros, MIN(a, b) and MAX(a, b). Read three numbers x lo hi and print x "clamped" into the range lo..hi: if it is below lo print lo, if above hi print hi, otherwise x. Use MIN(MAX(x, lo), hi).
Input
Three integers x, lo, hi (lo ≤ hi).
Output
The clamped value.
Example
Input
5 1 10
Output
5
Editor
C
Hints
Put brackets around every parameter in the macro.
Storing MAX(x, lo) in a variable first keeps the code simple.
Solution explanation
First we raise x to at least lo, then lower it to at most hi.
Show solution
#include <stdio.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main() {
int x, lo, hi;
scanf("%d %d %d", &x, &lo, &hi);
int raised = MAX(x, lo);
printf("%d\n", MIN(raised, hi));
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module