9. How Does C Do Math?

With Operators

image

There are two kinds of operators. There are the ones who help you with long distance phone calls, but we won’t be discussing those. There are also C operators, which let you do math. You don’t have to be a math wizard to write programs that use math operators. C does all the math for you as long as you know how to list the operators properly.

Not only should you learn to recognize math operators, but you should also learn how C orders math operators. C doesn’t always calculate from left to right. This chapter explains why.

The Basics

Lots of C operators work exactly the way you expect them to. You use a plus sign (+) when you want to add, and you use a minus sign (-) when you want to subtract. An expression includes one or more operators. C programmers often use math expressions on the right side of the assignment operator when filling variables with values, like this:

totalSales = localSales + foreignSales - salesReturns;

C computes the answer and then stores that answer in totalSales.

Clue

image

If you want to subtract a negative value, be sure to put a space between the minus signs, like this:

newValue = oldValue - -factor;

If you omit the space, C will think you’re using another operator, --, called the decrement operator, described in Chapter 13, “Are There More Operators?”.

You can even put a math expression inside a printf():

printf("In 3 years, I'll be %d years old. ", age + 3);

If you want to multiply and divide, you can do so by using the * and / symbols. The following statement assigns a value to a variable using multiplication and division:

newFactor = fact * 1.2 / 0.5;

Warning

image

If you put integers on both sides of the division symbol (/), C computes the integer division result. Study the following expressions to get familiar with integer division and regular division. The comments explain the results calculated from the divisions:

image

Note

image

If you need the remainder after integer division, use C’s modulus operator (%). Given the values just listed, the following statement puts a 2 in ansMod:

ansMod = i % j;  /* 2 is the remainder of 17 / 5 */

You now know the three ways C divides values: regular division if a noninteger is on either or both sides of the /, integer division if an integer is on both sides of the /, and modulus if the % operator is used between two integers.

Clue

image

You can’t use % between anything but integer data types.

The following short program computes the net sale price of tires:

image

Here is a sample run of the program:

image

Order of Operators

As mentioned earlier in this chapter, C doesn’t always compute math operations in the order you expect. The following expression explains it in a nutshell:

ans = 5 + 2 * 3;  /* Puts 11 in ans */

If you thought that C would store 21 in ans, you’re reading the expression from left to right. However, C always computes multiplication before addition! It sounds crazy, but as long as you know the rules, you’ll be okay. C is following the order of operators table. C first multiplies 2 and 3 to get 6 and then adds 5 to get 11.

You’ll find the complete order of operators table in the tearout card of this book. As you can see in the table, *, /, and % appear before + and -. Therefore, if C sees an expression with a combination of these operators, it evaluates *, /, and % before computing + and -.

Here is a difficult expression. All the variables and numbers are integers. See if you can figure out the answer by the way C would evaluate the expression:

ans = 5 + 2 * 4 / 2 % 3 + 10 - 3;  /* What is answer? */

The answer, 13, is found in Figure 9.1.

Figure 9.1. Solving the expression the way C would.

image

Clue

image

Don’t do too much at one time when evaluating such expressions for practice. As the figure shows, you should compute one operator at a time and then bring the rest of the expression down for the next round.

If an expression such as the one in Figure 9.1 contains more than one operator that sits on the same level in the order of operators table, you must use the third column, labeled Associativity, to determine how the operators are evaluated. In other words, because *, /, and % all reside on the same level, they were evaluated from left to right, as dictated by the order of operators table’s Associativity column.

You might wonder why you have to learn this stuff. After all, doesn’t C do your math for you? The answer is “Yes, but....” C does your math, but you need to know how to set up your expressions properly. The classic reason is as follows: Suppose you want to compute the average of four variables. The following will not work:

avg = i + j + k + l / 4;  /* Will NOT compute average! */

The reason is simple once you understand the order of operators. C computes the division first, so l / 4 is evaluated first and then i, j, and k are added to that divided result. If you want to override the order of operators, as you would do in this case, you have to learn to use ample parentheses around expressions.

Break the Rules with Parentheses

If you need to override the order of operators, you can. If you group an expression inside parentheses, C will evaluate that expression before the others. Because the order of operators table shows parentheses before any of the other math operators, parentheses have precedence, as the following statement shows:

ans = (5 + 2) * 3;  /* Puts 21 in ans */

Even though multiplication is usually performed before addition, the parentheses force C to evaluate 5 + 2 first and then multiplies the resulting 7 by 3. Therefore, if you want to average four values, you can do so by grouping the addition of the values in parentheses:

avg = (i + j + k + l) / 4;  /* Computes average */

Clue

image

Use lots of parentheses. They clarify your expressions. Even if the regular operator order will suffice for your expression, parentheses will make the expression easier for you to decipher if you need to change the program later.

Assignments Everywhere

As you can see from the order of operators table, the assignment operator has precedence and associativity, as do the rest of the operators. Assignment has very low priority in the table, and it associates from right to left.

The right-to-left associativity lets you perform an interesting operation: You can assign a value to more than one variable in the same expression. To assign the value of 9 to 10 different variables, you could do this:

a = 9; b = 9; c = 9; d = 9; e = 9;
f = 9; g = 9; h = 9; i = 9; j = 9;

but this is easier:

a = b = c = d = e = f = g = h = i = j = 9;

Because of the right-to-left associativity, C first assigns the 9 to j and then puts the 9 in i, and so on.

Clue

image

C doesn’t initialize variables for you. If you wanted 0 put in a bunch of variables, a multiple assignment would do it for you.

Rewards

image

• Use +, -, *, and / for addition, subtraction, multiplication, and division.

• Use % if you want the remainder of an integer division.

• Keep the order of operators table handy, because it determines how C evaluates expressions.

• Use multiple assignment operators if you have several variables to initialize.

Pitfalls

image

• Don’t put two minus signs together if you want to subtract a negative number. Leave a space between them.

• Don’t use % to compute the remainder of noninteger data division. If you divide nonintegers, the result will be an accurate floating-point answer.

• Don’t write long expressions without using parentheses. The parentheses help show exactly what you expect, and they keep you from incorrectly relying on the order of operator table.

In Review

C provides lots of math operators that do calculations for you. Most of the operators look like their math counterparts (+, -, /, and so on), and the others are easy to learn. The primary consideration you must concern yourself with is the order of operators. C’s order of operators table shows you the way C interprets the order of your calculations. You can use parentheses to override that built-in order if you like.

Code Example

image

Code Analysis

This series of assignment statements computes the total sale amount and the discount amount of a purchase. The cost of each item is first multiplied by the number of items bought. An 8 percent tax must be taken out of the total and then added back in. A 10 percent discount is computed from the grand total if the customer pays cash.

No parentheses are needed in any of the calculations because the natural order of operators works for the example. If you would like to make the order even clearer, you could add parentheses, such as in this rewritten last statement:

discounted = grandTotal - (.10 * grandTotal);

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset