6B. Function Libraries

Function libraries provide predefined functions for you. As noted earlier, we will only make limited use of libraries. But you can use some libraries, and this page discusses a few of them. Feel free to use any function mentioned on this page.


Including a library in your program

You need to request a library module in order to use what it provides. Function sqrt is part of the <cmath> library. To use <cmath>, put lines

  #include <cmath>
  using namespace std;
somewhere near the beginning of your program. (Notice that there is no semicolon at the end of the #include line, but there is a semicolon at the end of the using line.)

If you include several libraries, write a #include line for each, then write using namespace std; once.


The <cmath> library

In addition to sqrt(x), the <cmath> library provides the following.

pow(x, y)

pow(x, y) is (approximately) xy, where x and y are real numbers.

But to compute x2, you are better off writing x*x. It is much faster than pow(x, 2). Similarly, sqrt(x) is much faster than pow(x, 0.5).


abs(n)

abs(n) is the absolute value of int n.

fabs(x)

fabs(x) is the absolute value of real number x (of type double).


The <algorithm> library

The <algorithm> library provides the following useful functions.

max(u, v)

max(u, v) is the larger of u and v. For example, max(3, 7) = 7 and max(5, 5) = 5. This works for any numeric type.

min(u, v)

min(u, v) is the smaller of u and v. For example, min(3, 7) = 3 and min(3, 3) = 3. This works for any numeric type.


The <cstdio> library

Library <cstdio> provides printf and other functions that perform input and output. We will see more on input and output beginning on the next page.


The <cstdlib> library

Library <cstdlib> provides random, among many others.


Exercises

  1. What is the value of expression sqrt(25.0) Answer

  2. What is the value of expression max(3,8) Answer

  3. What is the value of expression max(2,2) Answer

  4. Is expression 2*sqrt(49) allowed? If so, what is its result? Answer

  5. Are statements

      double y = 10.0;
      double z = sqrt(y + 6);
    
    allowed? If so, what is the value of z? Answer