# Arithmetic Operators

An operator is a symbol that represents a specific action. We have discussed and used operators in prior chapters, including the assignment operator, =. C++ also supports operators for arithmetic, specifically addition, subtraction, multiplication, and division. Operators used for arithmetic are called, naturally enough, arithmetic operators. Table 4-1 summarizes them.

Table 4-1: Arithmetic Operators

Operator

Purpose

Example

Result

+

5 + 2

7

-

Subtraction

5 “ 2

3

*

Multiplication

5 * 2

10

/

Division ( Quotient )

5 / 2

2

%

Division (Remainder)

5 % 2

1

The % operator, also called the modulus operator, may look unfamiliar. It returns the remainder in division, and will be explained in the Division Operators section later in this chapter.

Arithmetic operators are binary operators because they operate on two operands , binary being a reference to 2, and operand referring to each of the two values that is in the arithmetic expression. For example, in the expression 5 + 2, the + sign is the operator, and the 5 and 2 each is an operand.

 Note Not all operators are binary. For example, in the expression “3, the negative sign, or negation operator, is a unary operator because it operates on only one operand, which is the integer 3 in this example. There also are ternary operators, which operate on 3 operands. However, all arithmetic operators involve two operands ”no more, no less.

The arithmetic operators work with negative as well as positive numbers, and, with the exception of the modulus operator, floating point numbers (numbers with values to the right of the decimal point) as well as whole numbers. The addition operator also works with strings as well as with numbers .

This chapter will demonstrate each of the arithmetic operators in a working program which tracks student enrollment in a course. The scenarios in the program are real world, based on my experience teaching computer science at a community college in the San Fernando Valley area of Los Angeles.

At the community college where I teach computer science, students often will pre-register, enrolling in a course before the semester starts. However, some students will add a course during the first few weeks of the semester.

The following program has two integer variables , total and added. The program first assigns to total the value inputted by the user for the number of preregistered students. The program then assigns to added the value inputted by the user for the number of students adding the course. Afterward, the program uses the addition operator to add two operands, total and added. The resulting sum is then assigned to total, which now reflects the number of all students in the course, both preregistered and added. That sum then is outputted.

` #include <iostream> using namespace std; int main(void) {  int total, added;  cout << "Enter number of pre-registered students: ";  cin >> total;  cout << "Enter number of students adding the course: ";  cin >> added;  total = total + added;  cout << "Total number of students: " << total;  return 0; } `

The input and output of the program could be

` Enter number of registered students: 30 Enter number of students adding the course: 3 Total number of students: 33 `

#### Combined Assignment and Arithmetic Operator

New programmers sometimes are confused by statements such as total = total + added because, in mathematics, a variable cannot equal itself plus another number. However, this statement is not made in mathematics, but in C++ programming, in which the = operator is not used for equality, but instead for assignment.

Nevertheless, there also is another way to express total = total + added:

` total += added; `

To the compiler, it makes no difference whether you use total = total + added or total += added. However, many programmers prefer total += added, some because it looks more elegant, others because it seems more readable, and still others for the practical reason that it requires less typing.

This compact form of combining arithmetic and assignment operators is not limited to the addition operator. As Table 4-2 shows, it also can be used with the other arithmetic operators. In that table, it is assumed a is a previously declared integer variable.

Table 4-2: Combining Arithmetic and Assignment Operators

Statement

Combining Operators

a = a + 2;

a +=2;

a = a “ 2;

a “=2;

a = a * 2;

a *=2;

a = a / 2;

a /=2;

a = a % 2;

a %=2;

#### Precedence Between Arithmetic and  Assignment  Operators

The statement total = total + added uses two operators, assignment and arithmetic. The arithmetic operation has precedence over the assignment operation. This means the addition is performed before the assignment. This makes more sense intuitively than the other order. However, as I will explain in detail later in this chapter, precedence also arises when more than one arithmetic operator is used in a statement, and there the correct order is less intuitive.

#### Overflow and Underflow

Overflow and underflow applies to the results of addition. The range of the int data type on my compiler and operating system is “2,147,483,648 to 2,147,483,647. Here is the result of my class starting with a very large preregistration, 2,147,483,647, and then adding one more student:

` Enter number of preregistered students: 2147483647 Enter number of students adding the course: 1 Total number of students: -2147483648 `

While negative inputs make no sense in this program since you can t have a negative number of students enroll in or add a class, other programs may use negative numbers, such as for below zero temperatures . Therefore, the following input uses negative numbers to illustrate underflow with the addition operator.

` Enter number of preregistered students: -2147483648 Enter number of students adding the course: -1 Total number of students: 2147483647 `

While we think of addition as involving numeric operands, the addition operator also can be used with string operands. The output of the following code is: Your name is JeffKent.

` #include <iostream> #include <string> using namespace std; int main(void) {  string firstName = "Jeff";  string lastName = "Kent";  cout << "Your name is " << firstName + lastName;  return 0; } `

Adding two strings has the effect of appending the second string operand to the first string operand. Appending means adding the contents of the second string to the end of the first string.

While you can add numbers and numbers, or strings and strings, attempting to add a number and a string will cause a compiler error. The addition operator may perform arithmetic addition with two numeric operands, or appending with two string operands, but it does not know how to add a numeric operand and a string operand.

### The Subtraction Operator

At the community college where I teach, students leave the class as well as join it. Some of the preregistered students never show up. Other students who show up later decide to drop the course.

The following program builds on the one we used with the addition operator by adding one integer variable, dropped for students who I dropped because they never showed up, or who dropped themselves from the course. The dropped variable is assigned a value by the user. The program then uses the subtraction operator to update total.

` #include <iostream> using namespace std; int main(void) {  int total, added, dropped;  cout << "Enter number of pre-registered students: ";  cin >> total;  cout << "Enter number of students adding the course: ";  cin >> added;  total = total + added;  cout << "How many students dropped? ";  cin >> dropped;  total -= dropped;  cout << "Total number of students: " << total << endl;  return 0; } `

The input and output of the program could be

` Enter number of pre-registered students: 30 Enter number of students adding the course: 3 How many students dropped? 5 Total number of students: 28 `

In this example, we used the combined assignment and arithmetic operator “= in the expression total “= dropped , rather than total = total “ dropped . As explained with the addition operator, either alternative will work the same way.

The effect of overflow and underflow are the same with the subtraction operator as with the addition operator. However, unlike the addition operator, the subtraction operator will not work with string operands.

### The Multiplication Operator

Returning to my community college course example, all students who enroll in a course owe a tuition of \$72, even if they don t show up or later drop the course.

The following program builds on the one we used with the addition operator by adding the following statement:

` cout << "Total tuition owed: \$" << (total + dropped) * 72   << endl; `

` #include <iostream> using namespace std; int main(void) {  int total, added, dropped;  cout << "Enter number of pre-registered students: ";  cin >> total;  cout << "Enter number of students adding the course: ";  cin >> added;  total = total + added;  cout << "How many students dropped? ";  cin >> dropped;  total -= dropped;  cout << "Total number of students: " << total << endl;  cout << "Total tuition owed:  \$" << (total + dropped) * 72  << endl;  return 0; } `

The input and output of the program could be

` Enter number of preregistered students: 30 Enter number of students adding the course: 3 How many students dropped? 5 Total number of students: 28 Total tuition owed: 76 `

The variables total and dropped are added so that total reflects all students ever enrolled, even if they are no longer in the class, because all students owe tuition even if they don t show up or later drop the course.

The effect of overflow and underflow are the same with the multiplication operator as with the addition and subtraction operators. Unlike the addition operator, but like the subtraction operator, the multiplication operator will not work with string operands.

#### Precedence Between Arithmetic Operators

The statement we added has two arithmetic operators, for addition and multiplication. The order in which the two arithmetic operations are performed makes a difference. If addition is performed first, 28 + 5, and then the sum, 33, is multiplied by 72, the result is 2376. However, if multiplication is performed first, 5 * 72, and then the product, 360, is added to 28, the result would be 388.

C++ has rules, called precedence, for determining which operation is performed first. Precedence was discussed earlier in this chapter in the section on the addition operator concerning the precedence of arithmetic operators over the assignment operator. However, here the issue is precedence between arithmetic operators.

Table 4-3 lists the precedence between arithmetic operators.

Table 4-3: Precedence of Arithmetic Operators

Precedence

Operator

Highest

“ (unary negation)

Middle

* / %

Lowest

+ “

When there is more than one operator in a row in Table 4-3, those operators have equal precedence. Thus, the multiplication operator and the two division operators have equal precedence. Similarly, the addition and subtraction operators have equal precedence.

Table 4-4 shows the results of applying precedence to several arithmetic expressions. We have not reviewed the division operators yet, but in the examples in Table 4-4 the / operator works exactly as it does in arithmetic.

Table 4-4: Precedence in Action

Expression

Result

2 + 3 * 4

14, not 20

8 / 2 “ 1

3, not 8

C++ also has rules called associativity for determining which operation is performed first when two operators have equal precedence. Table 4-5 describes those rules.

Table 4-5: Associativity of Arithmetic Operators

Operator

Associativity

(unary negation)

Right to left

* / %

Left to right

+ “

Left to right

Therefore, the result of the expression 8 / 2 * 4 is 16, not 1, because division, being the leftmost operator, is performed first.

However, there are times when you want to override the default precedence. For example, in our program, in calculating tuition, the default precedence would be to multiply dropped by 72, after which the product would be added to total. However, we want to change the order of operations so that dropped is first added to total, and the sum then multiplied by 72.

You can override the default precedence with parentheses. This is done in the statement:

` cout << "Total tuition owed: \$" << (total + dropped) * 72   << endl; `

Expressions in parentheses are done first. As a result of the parentheses, the expression (total + dropped) * 72 is evaluated so that dropped is first added to total, and the sum is then multiplied by 72.

### Division Operators

Addition, subtraction, and multiplication each have one operator. However, division has two. The / operator gives you the quotient, while the % (or modulus operator) gives you the remainder.

Quotient and remainder, along with dividend and divisor, are terms that I first learned in elementary school and then did not use very much again until many years later. If you are rusty on your arithmetic terminology like I was, this example may help. In the problem 7 divided by 2, 7 is the dividend and 2 is the divisor. The result of this division is that 3 is the quotient and 1 is the remainder.

#### The Division Operator

The division operator returns the quotient. However, the value of the quotient depends on whether at least one of the operands is a floating point data type.

For example, the value of 10 / 4 is 2.5. However, in C++, the value is 2 because, when both operands are an integer or other whole number data type, then the result is an integer as well, and the remainder is not part of the quotient. This is true even if the result is assigned to a floating point variable. The output of the following program is 10 / 4 = 2.

` #include <iostream> using namespace std; int main(void) {  int firstOp = 10, secondOp = 4;  float result = firstOp / secondOp;  cout << firstOp << " / " << secondOp << " = " << result;  return 0; } `

However, the value of 10.0 / 4 is 2.5 in C++. When at least one of the operands is a floating point data type, and 10.0 would be interpreted as floating point, then the result is a floating point as well. The output of the following program is 10 / 4 = 2.5 because we changed the data type of firstOp from int to float:

` #include <iostream> using namespace std; int main(void) {  float firstOp = 10, result;  int secondOp = 4;  result = firstOp / secondOp;  cout << firstOp << " / " << secondOp << " = " << result;  return 0; } `

Going back to the first example, if you want the result of the division of two integer variables to be a float, then you have to cast one of the variables to a float. A cast does not change the data type of the variable, just the data type of the value of the variable during the completion of the operation. You cast the variable by putting the desired data type in front of it in an expression, and placing either the desired data type or the variable in parentheses. This is how the first example could be changed to make the result of integer division a float:

` #include <iostream> using namespace std; int main(void) {  int firstOp = 10, secondOp = 4;  float result = (float) firstOp / secondOp;  cout << firstOp << " / " << secondOp << " = " << result;  return 0; } `

All of the following expressions would work

` float result = (float) firstOp / secondOp; float result = float (firstOp) / secondOp; float result = firstOp / (float) secondOp; float result = firstOp / float (secondOp); `

However, in some programs you may want integer division so that the quotient will ignore the fractional value. The Change Machine project later in the chapter is an example.

Let s now put this into practice with the student enrollment program. In the last modification to this program, tuition was calculated based on all students who ever enrolled in the course, even if they no longer were in the course. The addition to the program calculates and displays the average tuition per student still enrolled. An integer variable tuition is added to store the total tuition collected, which is calculated using the expression (total + dropped) * 72. The average tuition per student still enrolled then is calculated and displayed with the statement:

` cout << "Average tuition per enrolled student: \$"  << (float)  tuition / total; `

` #include <iostream> #include <string> using namespace std; int main(void) {  int total, added, dropped, tuition;  cout << "Enter number of preregistered students: ";  cin >> total;  cout << "Enter number of students adding the course: ";  cin >> added;  total = total + added;  cout << "How many students dropped? ";  cin >> dropped;  total -= dropped;  cout << "Total number of students: " << total << endl;  tuition = (total + dropped) * 72;  cout << "Total tuition owed: \$" << tuition << endl;  cout << "Average tuition per enrolled student: \$"   << (float) tuition / total;  return 0; } `

The input and output could be

` Enter number of preregistered students: 30 Enter number of students adding the course: 3 How many students dropped? 5 Total number of students: 28 Total tuition owed: 76 Average tuition per enrolled student: .8571 `

The casting of one of the operands to a float is necessary. Otherwise, the average tuition would be \$84 instead of \$84.8571.

#### The Modulus Operator

The modulus operator also involves division, but returns only the remainder. For example, the result of 7 % 2 is not the quotient, 3, but the remainder, 1.

The modulus operator works only with whole number operands. The result of an attempt to use it with a floating point operand is undefined . The result often is a compiler error, but this is compiler dependent.

The modulus operator will be used in the Change Machine project later in this chapter.

 Caution Whether you use the / or the % operator, you cannot divide by zero. The result is an error.

### Exponents

C++, unlike some other programming languages, does not have an exponent operator. Instead, it has a built-in function named pow , which is defined in the standard library cmath. The name pow is shorthand for power, since with exponents one number is raised to the power of another.

The pow function has two arguments. The first argument is the number that is being raised to a certain power. The second argument is the power the first argument is being raised to. Therefore, the expression pow (4, 2) would be used to raise 4 to the power of 2, the result being 16.

While in the example 4 to the power of 2, the result is a whole number, the pow function returns a double data type. Floating point numbers also can be raised to a power, resulting in another floating point number. Additionally, whole numbers can be raised to a negative power, which also may result in a floating point number.

The pow function is useful for solving math problems. The formula for the area of a circle is area = p r 2 . Assuming a value of p of 3.14159, two double variables area and radius, and that radius has already been assigned a value, the code for determining the circle s area is

` area = 3.14159 * pow(radius, 2); `

The following program calculates the area of a circle based on a radius inputted by the user.

` #include <iostream> #include <cmath> using namespace std; int main(void) {  double radius, area;  cout << "Enter radius of circle: ";  cin >> radius;  area = 3.14159 * pow(radius, 2);  cout << "The area is " << area << endl;  return 0; } `

The input and output could be

` Enter radius of circle: 6 The area is 113.097 `

C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148