Small Steps VI — Growing into C++
Finding the magnitude of a negative number
Find the magnitude of a negative number.
What you will learn
An absolute value is a number's distance from 0 on the number line. Find it with std::abs.
Try it
Example · example2.cpp
void small_main()
{
int a = -12;
int b = 7;
print("Absolute: ", std::abs(a));
print("Smaller: ", std::min(a, b));
}
The absolute value of -12 is 12. The expected output is Absolute: 12 and Smaller: -12.
Knowing a function's name, input, and result lets you use it without recreating its implementation. Value ranges are limited, so practice with small integers here.
Exercise
Find and print the absolute value of -25 using std::abs.
Exercise starter · exercise2_starter.cpp
void small_main()
{
// Use a Standard Library function.
}
Hint
std::abs(-25) returns the int 25.
show solution
void small_main()
{
print(std::abs(-25));
}