15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

164<br />

Using Math to Manipulate Numbers<br />

Organizing equations with operator precedence<br />

To do multiple calculations, you can type one mathematical calculation after<br />

another, such as<br />

X = 34 + 7<br />

Y = X * 89<br />

Although this works, it can get clumsy, especially if you need to write more<br />

than a handful of equations. As a simple solution, you can cram multiple<br />

equations into a single, big equation, such as<br />

Y = 34 + 7 * 89<br />

The problem is, how does the computer calculate this equation? Does it first<br />

add 34 + 7 and then use this result (41) to multiple with 89? Or does it first<br />

multiply 7 by 89 and then add this result (623) to 34?<br />

Depending on the order it calculates its mathematical operators, the result is<br />

either 3649 or 657, two obviously different answers.<br />

To calculate any equation with multiple mathematical operators, computers<br />

follow rules that define which mathematical operators get calculated first<br />

(known as operator precedence). Table 3-3 lists common operator precedence<br />

<strong>for</strong> most <strong>programming</strong> languages where the top operators have the<br />

highest precedence, and the lowest operators at the bottom of the table<br />

have the lowest precedence.<br />

Table 3-3<br />

Operator<br />

Symbol<br />

Exponentiation<br />

^<br />

Multiplication *<br />

Division /<br />

Integer division \<br />

Modulus arithmetic % or mod<br />

Addition +<br />

Subtraction –<br />

Operator Precedence<br />

If an equation contains operators that have equal precedence, the computer<br />

calculates the result from left to right, such as<br />

X = 8 - 3 + 7<br />

First, the computer calculates 8 – 3, which is 5 Then it calculates 5 + 7,<br />

which is 12.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!