C++
Number helpers
Add number conversion and calculation functions.
Number helpers
Now we add a number helper to the Helpers class: clamp. This method keeps a value within a range. If the value is below the minimum it returns the minimum; if above the maximum it returns the maximum; otherwise it returns the value itself.
Example: static int clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; }. The call Helpers::clamp(15, 0, 10) returns 10, because 15 is greater than 10. clamp(-3, 0, 10) returns 0. This method is useful for clamping game scores, screen coordinates or percentage values.
Using clamp
Calling clamp is just like capitalize: Helpers::clamp(15, 0, 10). After the previous lessons' output, we print the result on a new line. The output keeps accumulating.
Output order: Ready, Hello, 10. Each lesson keeps the previous output and adds a new one. This shows the helper library growing step by step. The int value returned by clamp can be printed directly with std::cout; no conversion is needed.
Exercise Add the clamp method and call it
Take the previous lesson's solution (Helpers class has the capitalize method). Under public: add static int clamp(int value, int min, int max) with body if (value < min) return min; if (value > max) return max; return value;. In main after the capitalize call add std::cout << std::endl << Helpers::clamp(15, 0, 10);.
Show example solution
#include <iostream>
#include <string>
#include <cctype>
class Helpers {
public:
static std::string capitalize(std::string text) {
if (text.empty()) return text;
text[0] = std::toupper(text[0]);
return text;
}
static int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
};
int main() {
std::cout << "Ready" << std::endl;
std::cout << Helpers::capitalize("hello") << std::endl;
std::cout << Helpers::clamp(15, 0, 10);
return 0;
}
Test yourself
-
Complete the clamp body
if (value < min) return min; if (value > ____) return max; return value;
Show answer
if (value < min) return min; if (value > max) return max; return value;
-
What is the result of Helpers::clamp(15, 0, 10)?
Helpers::clamp(15, 0, 10)
Show answer
10 — 15 is greater than 10, so 10 is returned.
-
Match each call to its result
- clamp(15, 0, 10)
- returns 10
- clamp(-3, 0, 10)
- returns 0
- clamp(5, 0, 10)
- returns 5
Next lesson: Date helpers