On this mastery I will show you what are libraries in C++ and how to use them.

As you may have noticed, the first line of code we’ve been using is always #include <iostream>. This is called a library and they contain commands that you can use in your program. There are more of them, and you can check a list of libraries and their uses here

Library iostream includes the usage of cin and cout in our program, and strictly talking, that’s all we’ve been using for our programs. There’s a library called cmath that includes the usage of more complex mathematical operations. We are going to focus of this library today and use the command for square root, this library will allow us to simply use the command sqrt instead of making all the manual calculations. So, do as follows:

  1. Open the program we made in mastery 24
  2. Add a variable called squareroot.
  3. After the for loop, add the math operation with the new variable and the cmath command: squareroot = sqrt(total)
  4. Print the result.

Your program should look something like this:

Now let’s run it:

Great! Now you know what are libraries and how to use them, congrats!

CC BY 4.0 Mastery 13 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.