03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

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

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

26 CHAPTER 2. <strong>C++</strong> BASICS<br />

Operator Action<br />

− subtraction, also unary minus<br />

+ addition<br />

∗ multiplication<br />

/ division<br />

% modulus<br />

−− decrement<br />

++ increment<br />

The modulus operator yields the remainder of the integer division. The ++ operator adds one<br />

to its operand and −− subtracts one. Both can precede or follow the operand. When they<br />

precede the operand, the corresponding operation will be per<strong>for</strong>med be<strong>for</strong>e using the operand’s<br />

value to evaluate the rest of the expression. If the operator follows its operand, C ++ will use<br />

the operand’s value be<strong>for</strong>e incrementing or decrementing it. Consider the following example:<br />

x = 1;<br />

y = ++x;<br />

x = 1;<br />

z = x++;<br />

As a result of executing these four lines of code, y will be set to 2, x will be set to 2 and z will<br />

be set to 1.<br />

The priority and associativity of binary arithmetic operators is the same as we know it from<br />

math: multiplication and division precedes addition and subtraction. Thus, x + y ∗ z is evaluated<br />

as x + (y ∗ z). Operations of the same priority are left-associative, i.e. x / y ∗ z is<br />

equivalent to (x / y) ∗ z. Unary operators have precedence over binary: x ∗ y++ / −z means<br />

(x ∗ (y++)) / (−z). Nevertheless, as long as you are still learning C ++ and not entirely sure<br />

about the precedences, you might want to add redundant parenthesis instead of wasting hours<br />

debugging your program.<br />

With these operators we can write our first numeric program:<br />

#include <br />

int main ()<br />

{<br />

float r1 = 3.5, r2 = 7.3, pi = 3.14159;<br />

float area1 = pi ∗ r1∗r1;<br />

std::cout ≪ ”A circle of radius ” ≪ r1 ≪ ” has area ”<br />

≪ area1 ≪ ”.” ≪ std::endl;<br />

std::cout ≪ ”The average of ” ≪ r1 ≪ ” and ” ≪ r2 ≪ ” is ”<br />

≪ (r1+r2)/2 ≪ ”.” ≪ std::endl;<br />

return 0 ;<br />

}<br />

2.3.2 Boolean operators<br />

Boolean operators are logical and relational operators. Both return boolean values, there<strong>for</strong>e<br />

the name. Operators and their significations are:

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

Saved successfully!

Ooh no, something went wrong!