Performing Mathematical Operations - Getting Started with C++ Programming - C++ For Dummies (2014)

C++ For Dummies (2014)

Part I

Getting Started with C++ Programming

Chapter 3

Performing Mathematical Operations

In This Chapter

arrow Defining mathematical operators in C++

arrow Using the C++ mathematical operators

arrow Identifying expressions

arrow Increasing clarity with special mathematical operators

C++ offers all the common arithmetic operations: C++ programs can multiply, add, divide, and so forth. Programs have to be able to perform these operations to get anything done. What good is a health insurance program if it can’t calculate how much you’re supposed to (over) pay?

C++ operations look like the arithmetic operations you would perform on a piece of paper, except you have to declare any variables before you can use them (as detailed in Chapter 2):

int var1;
int var2 = 1;
var1 = 2 * var2;

This code snippet declares two variables, var1 and var2. It initializes var2 to 1 and then stores the results of multiplying 2 times the value of var2 into var1.

This chapter describes the complete set of C++ mathematical operators.

Performing Simple Binary Arithmetic

A binary operator is one that has two arguments. If you can say var1 op var2, op must be a binary operator. The most common binary operators are the simple operations you performed in grade school. The binary operators are flagged in Table 3-1. (This table also includes the unary operators, which I describe a little later in this chapter.)

Table 3-1 Mathematical Operators in Order of Precedence

Precedence

Operator

What It Is

1

+ (unary)

Effectively does nothing

1

- (unary)

Returns the negative of its argument

2

++ (unary)

Increment

2

-- (unary)

Decrement

3

* (binary)

Multiplication

3

/ (binary)

Division

3

% (binary)

Modulo

4

+ (binary)

Addition

4

- (binary)

Subtraction

5

=, *=,%=,+=,-= (special)

Assignment types

Multiplication, division, modulus, addition, and subtraction are the operators used to perform arithmetic. In practice, they work just like the familiar arithmetic operations as well. For example, using the binary operator for division with a floating point double variable looks like this:

double var = 133.0 / 10.0;

image The expression 133/10 performs integer division, producing the int result 13 rather than the floating-point 13.3.

Each of the binary operators has the conventional meaning that you studied in grammar school — with one exception. You may not have encountered modulus in your studies. The modulus operator (%) works much like division, except it produces the remainder after division instead of the quotient. For example, 4 goes into 14 three times with a remainder of 2. Thus we say 14 modulus 4 is 2:

int var = 14 % 4; // var is set to 2

Modulus is not defined for floating point variables. (I discuss round-off errors in Chapter 2.)

Decomposing Expressions

The most common type of statement in C++ is the expression. An expression is a C++ statement with a value. Every expression also has a type, such as int, double, or char. A statement involving any mathematical operator is an expression since all these operators return a value. For example, 1 + 2 is an expression whose value is 3 and type is int. (Remember that a constant without a decimal point is of type int.)

Expressions can be complex or extremely simple. In fact, the statement 1 is an expression because it has a value (1) and a type (const int). The following statement has six expressions:

z = x * y + w;

The expressions are

x
y
w
x * y
x * y + w
z = x * y + w

Determining the Order of Operations

All operators perform some defined function. In addition, every operator has a precedence — a specified order in which the expressions are evaluated. Consider, for example, how precedence affects solving the following problem:

int var = 2 * 3 + 1;

If the addition is performed before the multiplication, the value of the expression is 2 times 4, or 8. If the multiplication is performed first, the value is 6 plus 1, or 7.

The precedence of the operators determines who goes first. Table 3-1 shows that multiplication has higher precedence than addition, so the result is 7. (The concept of precedence is also present in arithmetic. C++ adheres to the common arithmetic precedence.)

So what happens when two operators of the same precedence appear in the same expression? For example:

int var = 8 / 4 / 2;

When operators of the same precedence appear in the same expression, they are evaluated from left to right (the same rule applied in arithmetic). Thus, in this code snippet, var is equal to 8 divided by 4 (which is 2) divided by 2 (which is 1).

The expression

x / 100 + 32

divides x by 100 before adding 32. But what if the programmer wanted to divide x by 100 plus 32? The programmer can change the precedence by bundling expressions together in parentheses (shades of algebra!), as follows:

x /(100 + 32)

This expression has the same effect as dividing x by 132. The original expression

x / 100 + 32

is identical to the expression

(x / 100) + 32

Performing Unary Operations

Arithmetic binary operators — those operators that take two arguments — are familiar to a lot of us from school days. But consider the unary operators, which take a single argument (for example, -a). Many unary operations are not so well known.

The unary mathematical operators are plus, minus, plus-plus, and minus-minus (respectively, +, -, ++, and - -). The minus operator changes the sign of its argument. Positive numbers become negative and vice versa. The plus operator does not change the sign of its argument. The plus operator is rarely, if ever, used.

int var1 = 10;
int var2 = -var1; // var2 is now -10

The latter expression uses the minus unary operator (-) to calculate the value negative 10.

The ++ and the - - operators might be new to you. These operators (respectively) add one to their arguments or subtract one from their arguments, so they’re known (also respectively) as the increment and decrement operators. Because they’re dependent upon numbers that can be counted, they’re limited to non-floating point variables. For example, the value of var after executing the following expression is 11:

int var = 10; // initalize var
var++; // now increment it
// value of var is now 11


Why define a separate increment operator?

The authors of C++ noted that programmers add 1 more than any other constant. To provide some convenience, a special add 1 instruction was added to the language. In addition, most present-day computer processors have an increment instruction that is faster than the addition instruction. Back when C++ was created — with microprocessors being what they were — saving a few instructions was a big deal. Today, not so much.


The increment and decrement operators are peculiar in that both come in two flavors: a prefix version and a postfix version (known as pre-increment and post-increment, respectively). Consider, for example, the increment operator (the decrement works in the same way).

Suppose that the variable n has the value 5. Both ++n and n++ increment n to the value 6. The difference between the two is that the value of ++n is the value after incrementing (6) while the value of n++ is the value before incrementing (5). The following example illustrates this difference:

// declare three integer variables
int n1, n2, n3;


n1 = 5;
n2 = ++n1; // the value of both n1 and n2 is now 6


n1 = 5;
n3 = n1++;// the value of n1 is 6 but the value of n3 is 5

Thus n2 is given the value of n1 after n1 has been incremented (using the pre-increment operator), whereas n3 gets the value of n1 before it is incremented using the post-increment operator.

Using Assignment Operators

An assignment operator is a binary operator that changes the value of its left argument. The equal sign (=), a simple assignment operator, is an absolute necessity in any programming language. This operator puts the value of the right-hand argument into the left-hand argument. The other assignment operators are odd enough that they seem to be someone’s whim.

So what about the following:

int var1;
int var2 = 2;
var1 = var2 = 1;

If we used the left to right rule, var1 ends up with the value 2 but var2 with the value 1, which is counterintuitive. To avoid this, multiple assignment operators are evaluated from right to left. Thus, the example snippet assigns the value 1 to var2 and then copies the same value into var1.

The creators of C (from which C++ originated) noticed that assignments often follow the form of

variable = variable # constant

where # is some binary operator. Thus, to increment an integer operator by 2, the programmer might write

nVariable = nVariable + 2;

This expression says, “Add 2 to the value of nVariable and store the results back into nVariable.” Doing so changes the value of nVariable to 2 more than it was.

Because the same variable appears on both sides of the = sign, the same Fathers of the C Revolution decided to create a version of the assignment operator with a binary operator attached. This says, in effect, “Thou shalt perform whatever operation on a variable and store the results right back into the same variable.”

Every binary operator has one of these nifty assignment versions. Thus, the assignment just given could have been written this way:

nVariable = nVariable + 2;
nVariable += 2;

Here the first line says (being very explicit now), “Take the value of nVariable, add 2, and store the results back into nVariable.” The next line says (a bit more abruptly), “Add 2 to the value of nVariable.

image Other than assignment itself, these assignment operators are not used all that often. However, as odd as they might look, sometimes they can actually make the resulting program easier to read