C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

9. Crunching the Numbers—Letting C Handle Math for You


In This Chapter


  • Handling basic arithmetic

  • Understanding order of operators

  • Breaking the rules with parentheses

  • Using assignments everywhere


Many people still break out in a cold sweat when they are told that they will have to do some math.
Luckily, computers don’t mind math, and as long as you enter the numbers correctly, your C program
will always do your math right with the use of operators. The term operators might conjure images of
the ladies that used to help with long-distance phone calls, but we aren’t discussing those. These are
C operators, which let you do math. You don’t have to be a math wizard to write programs that use
math operators.


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.


Basic Arithmetic


A lot 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:


Click here to view code image


totalSales = localSales + internationalSales - salesReturns;

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


Note

If you want to subtract a negative value, be sure to put a space between the minus signs,
like this:
Click here to view code image
newValue = oldValue - -factor;
If you omit the space, C thinks you’re using another operator, --, called the decrement
operator, described in Chapter 13, “A Bigger Bag of Tricks—Some More Operators
for Your Programs.”

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

Free download pdf