“Math” is a simple word that comprises complex concepts, formulas, and functions. Math performs exactly the same way in C++ as it does in the physical world. Within C++ it’s possible to do anything from simple arithmetic to algebra, trigonometry, and calculus.
In this article, we take a look at how math operations that we see in everyday life appear in C++ and how to use them effectively in your code.
Arithmetic in C++
It comes as no surprise that arithmetic in C++ uses the same operations you learned in elementary school. C++ programmers can even use the modulus operator to output the remainder of a division equation. Here are the operators C++ uses to designate each type of arithmetic expression:
Operation | Operator |
Addition | + |
Subtraction | – |
Multiplication | * |
Division | / |
Remainder (Modulus) | % |
At a glance, here’s how each of these look in code. Every cout
printing command outputs the result of the arithmetic expression that follows:
#include <iostream> |
Each math operation returns the value you would expect, including the modulus operator where 9 divided by 4 is 2 with a remainder of 1 (accordingly, with 1 as the output).
14 |
Rules of Math in C++
Whether doing some math in C++ or in the real world, there are certain rules that you must follow to reach a correct solution.
Order of Operations
When performing arithmetic, the order of operations shows which math calculations are done first. Remembering the acronym PEMDAS will go a long way toward helping you to understand the order quickly. PEMDAS stands for the following:
Order | Abbreviation | Meaning |
1st | P | Parentheses |
2nd | E | Exponents |
3rd | MD | Multiplication and Division |
4th | AS | Addition and Subtraction |
In the following code snippets, you will see that C++ first scans your math expression — from left to right — for parentheses and will perform any action within, using the remaining PEMDAS steps within nce that’s complete, evaluation of the top-level expression continues: exponents will be done, then multiplication and division, and, lastly, addition and subtraction.
Note that multiplication and division share the same precedence, followed by addition and subtraction.
Let’s see how this plays out in code. We’ll be visiting exponents in a little bit, as they’re more complex. Take a look at the example below:
#include <iostream> |
As you can see, it doesn’t matter in which order we write our calculation. Math in C++, following PEMDAS, will always perform the multiplication first.
x is 35, y is 35 |
Switching things up ever so slightly leads to a completely different result:
#include <iostream> |
The program will perform calculations on any integers/values appearing inside of parentheses, before moving on to those outside of them. For x in this example, the code will do the addition inside of the parentheses before doing the multiplication. The results are no longer the same as in the previous example:
x is 51, y is 35 |
Arithmetic With Different Data Types
The data types in C++ represent different types of numbers. We use the int
data type for integer values and float
and double
for values that have decimal points.
When it comes to math in C++, the programming language offers multiple data types for working with decimal-notation numbers. Take a look at the example below:
#include <iostream> |
C++ will output a result based upon the values used for the input when you don’t assign a data type to an output. Even when we do assign a data type, C++ will give us an output based upon the simplest value in our equation.
Even with decimal places in the equation, int will always return an integer. Subsequently, using a float data type won’t add decimal places to the output if our input values are both integers.
The four outputs of the above code return the following:
12.4 |
Maximums and Minimums in C++
The max()
and min()
functions will output the highest or lowest value of two inputs:
#include <iostream> |
Our variable maxval
becomes the highest number of the two values of our max()
function. Looking at the min()
function, the program will either output 10 or the user’s value depending on which is lower. You can use this mechanism, for example, in if/else statements or loops.
Should you want the program to output the maximum of three (or more) values, you’ll need to use multiple max()
functions:
#include <iostream> |
This code does output 10 as the result.
Additional Types of Math Operations
As mentioned earlier, you can also use C++ to perform more complex mathematical formulae. To access these other types of operations, you’ll need to use the math library from C++ by including cmath
at the beginning of your program:
#include <iostream> |
There are a multitude of math-based functions in C++. Let’s visit some of the more common ones.
Exponents in C++
With the cmath library in place, we can finally circle back to exponential equations in C++. To do so, we must call upon the pow()
function:
pow(base number, exponent) |
In code, this looks as follows:
#include <iostream> |
This bit of code takes the base value 2 to the 5th power (25), for a result of 32.
Square Roots in C++
Heading in the opposite direction, we can use the sqrt()
function to determine the square root of a particular value.
#include <iostream> |
It may be wise to use the double
data type here should the value you’re taking the square root of not be a perfect square (winding up with a fractional part, which would be thrown away when storing the result in a variable of data type int
.
Because a double is used the above code prints out 15.8745.
Rounding in C++
If you wish to round a double
or float
result to the nearest integer, use the round()
function. Keep in mind that this is different from changing the data type to int
, which would truncate the decimal values without rounding the value up.
#include <iostream> |
15.8745 is rounded up to a value of 16.
Learn C++ Online With Udacity
We’ve covered quite a bit of C++ in this article, including arithmetic, exponents, and rounding. That said, we’re merely scraping the surface of what’s possible with C++. The language has applications ranging from gaming to browsers, so taking the time to learn it could result in a game-changing career move.
At Udacity, our C++ experts have designed a hands-on nanodegree program that will teach you what you need to know to start a successful career in C++ programming.