Computer Programming Week 4: Operators

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Computer Programming

Week 4
Operators

13.10.2014

C# provides an extensive set of operators that give the


programmer detailed control over the construction and evaluation
of expressions. Most of C#s operators fall into the following
categories:




arithmetic,
relational,
and logical.

These operators are examined in this chapter.

13.10.2014

Arithmetic Operators

C# defines the following arithmetic operators (Table 5.1):

Table 5.1 Arithmetic Operators

13.10.2014

Although the actions of arithmetic operators are well known to all


readers, a few special situations warrant some explanation.

First, remember that when / is applied to an integer, any remainder will


be truncated; for example, 10/3 will equal 3 in integer division.

You can obtain the remainder of this division by using the modulus
operator, %. The % is also referred to as the remainder operator. It
yields the remainder of an integer division. For example, 10 % 3 is 1. In
C#, the % can be applied to both integer and floating-point types. Thus,
10.0 % 3.0 is also 1.

Example shows % operator for int and double type (Figure 5.1)

13.10.2014

13.10.2014

Figure 5.1 Example of % operator

As you can see, the % yields a remainder of 1 for both integer and
floating-point operations.

13.10.2014

Arithmetic expressions must be written in straight-line form to


facilitate entering applications into the computer. Thus, expressions
such as a divided by b must be written as a/b, so that all constants,
variables and operators appear in a straight line. The following
algebraic notation is generally not acceptable to compilers:

a
b


Parentheses are used to group terms in C# expressions in the


same manner as in algebraic expressions. For example, to
multiply a times the quantity b+c, we write

13.10.2014

C# applies the operators in arithmetic expressions in a precise


sequence determined by the following rules of operator
precedence, which are generally the same as those followed in
algebra (Table 5.2)

Table 5.2 Operator precedence


13.10.2014

Now let us consider several expressions in light of the rules of


operator precedence. Each example lists an algebraic expression
and its C# equivalent.

The parentheses are required because division has higher


precedence than addition. The entire quantity ( a + b + c + d + e ) is
to be divided by 5. If the parentheses are erroneously omitted, we
obtain a + b + c + d + e / 5, which evaluates as

13.10.2014

The following is an example of the equation of a straight line:

No parentheses are required. The multiplication operator is applied


first, because multiplication has a higher precedence than addition.
The assignment occurs last, because it has a lower precedence
than multiplication or addition.
The following example contains remainder (%), multiplication,
division, addition and subtraction operations:

13.10.2014

10

The circled numbers under the statement indicate the order in which
C# applies the operators. The multiplication, remainder and division
operations are evaluated first in left-to-right order (i.e., they
associate from left to right), because they have higher precedence
than addition and subtraction. The addition and subtraction
operations are evaluated next. These operations are also applied
from left to right.

To develop a better understanding of the rules of operator


precedence, consider the evaluation of a second-degree polynomial
(y = ax2 + bx + c):

13.10.2014

11

Suppose that a, b, c and x in the preceding second-degree


polynomial are initialized (given values) as follows: a = 2, b = 3, c =
7 and x = 5 (Figure 5.2)

13.10.2014

Figure 5.2 Operator precedence steps

12

Mode of Arithmetic Results




If the two operands of an arithmetic operation are of the int data type
the result is an int value. If the two operands are float the result
is float. If the two operands are of the same data type the result is
the same data type as the operands. If the two operands are mixed,
(e.g., one operand is int and the other is float, the arithmetic is
known as mixed-mode arithmetic) and the result has the float data
type.Table 5.3 shows the data type of the result when mixed-mode
arithmetic is involved. The following examples show mixed-mode
operations:

13.10.2014

Table 5.3 Mixed mode arithmetic

13

Mode of Arithmetic Results

When arithmetic is performed using both integer and floating-point


operands, the computer has to change the integer operand to a
floating-point number before performing the arithmetic, for example

13.10.2014

14

Increment and Decrement




The ++ and the are the increment and decrement operators.


As you will see, they have some special properties that make
them quite interesting. Lets begin by reviewing precisely what
the increment and decrement operators do.

The increment operator adds 1 to its operand, and the decrement


operator subtracts 1. Therefore,
x = x + 1;
is the same as
x++;

13.10.2014

15

Increment and Decrement


x = x - 1;
is the same as
x--;


Understand, however, that in the increment or decrement forms,


x is evaluated only once, not twice. This can improve efficiency in
some cases.

13.10.2014

16

Increment and Decrement




Both the increment and decrement operators can either precede


(prefix) or follow (postfix) the operand. For example
x = x + 1;
can be written as
++x; // prefix form
or as
x++; // postfix form
In the previous example, there is no difference whether the
increment is applied as a prefix or a postfix. However, when an
increment or decrement is used as part of a larger expression,
there is an important difference.

13.10.2014

17

Increment and Decrement




When an increment or decrement operator precedes its operand, the


result of the operation is the value of the operand after the increment. If
the operator follows its operand, the result of the operation is the value
of the operand before the increment. Consider the following:
x = 10;
y = ++x;

In this case, y will be set to 11. This is because x is first incremented


and then its value is returned. However, if the code is written as
x = 10;
y = x++;

then y will be set to 10. In this case, the value of x is first obtained, x is
incremented, and then the original value of x is returned. In both cases,
x is still set to 11. The difference is what is returned by the operation.

13.10.2014

18

13.10.2014

19

y= y+ x++

y= y+ ++x

10

14

15

10

20

14

21

15

27

20

28

21

35

27

36

28

44

35

45

36

54

44

10

55

45

10

65

54

11

13.10.2014

20

Figure 5.3 The difference between prefix and postfix

13.10.2014

21

As the output confirms, the statement


y = y + x++;
adds the current values of x and y, and assigns this result back to
y. The value of x is incremented after its value has been
obtained. However, the statement
y = y + ++x;
obtains the value of x, increments x, and then adds that value to
the current value of y. This result is assigned to y. As the output
shows, simply changing ++x to x++ changes the number series
quite substantially.

13.10.2014

22

Relational and Logical Operators




In the terms relational operator and logical operator, relational


refers to the relationships that values can have with one another,
and logical refers to the ways in which true and false values can
be connected together. Since the relational operators produce
true or false results, they often work with the logical operators.
For this reason they will be discussed together here.

The relational and logical operators are as follows (Table


5.4,Table 5.5):

13.10.2014

23

Table 5.4 The relational operators

Table 5.5 The logical operators


13.10.2014

24

The outcome of the relational and logical operators is a bool


value.

In general, objects can be compared for equality or inequality


using == and !=. However, the comparison operators, <,>,<=, or
>=, can be applied only to those types that support an ordering
relationship. Therefore, all of the relational operators can be
applied to all numeric types.

For the logical operators, the operands must be of type bool, and
the result of a logical operation is of type bool. The logical
operators, &, |, ^, and !, support the basic logical operations AND,
OR, XOR, and NOT, according to the following truth Table 5.6:

13.10.2014

25

Table 5.6 The basic logical operations AND, OR, XOR, and NOT

As the table shows, the outcome of an exclusive OR (XOR)


operation is true when one and only one operand is true.

13.10.2014

26

13.10.2014

27

Figure 5.4 Several Examples of the Relational and Logical Operators

13.10.2014

28

Short-Circuit Logical Operators




C# supplies special short-circuit versions of its AND and OR logical


operators that can be used to produce more efficient code. To
understand why, consider the following.

In an AND operation, if the first operand is false, then the outcome is


false no matter what value the second operand has.

In an OR operation, if the first operand is true, then the outcome of the


operation is true no matter what the value of the second operand. Thus,
in these two cases there is no need to evaluate the second operand. By
not evaluating the second operand, time is saved and more efficient
code is produced.

13.10.2014

29

Short-Circuit Logical Operators




The short-circuit AND operator is && and the short-circuit OR operator


is ||. As described earlier, their normal counterparts are & and |. The
only difference between the normal and short-circuit versions is that the
normal operands will always evaluate each operand, but short-circuit
versions will evaluate the second operand only when necessary.

Here is a program that demonstrates the short-circuit AND operator


(Figure 5.5). The program determines if the value in d is a factor of n. It
does this by performing a modulus operation. If the remainder of n / d is
zero, then d is a factor. However, since the modulus operation involves
a division, the short-circuit form of the AND is used to prevent a divideby-zero error.

13.10.2014

30

13.10.2014

31

13.10.2014

32

Figure 5.5 Example that demonstrates the short-circuit AND operator




To prevent a divide-by-zero error, the if statement first checks to see if d


is equal to zero. If it is, then the short-circuit AND stops at that point
and does not perform the modulus division. Thus, in the first test, d is 2
and the modulus operation is performed. The second test fails because
d is set to zero, and the modulus operation is skipped, avoiding a
divide- by-zero error. Finally, the normal AND operator is tried. This
causes both operands to be evaluated, which leads to a runtime error
when the division-by-zero occurs.

13.10.2014

33

The lesson here is that if your code expects the


right-hand operand of an AND or OR operation to be
evaluated, then you must use C#s non-short-circuit
forms for these operations.
One other point: The short-circuit AND is also known
as the conditional AND, and the short-circuit OR is
also called the conditional OR.

13.10.2014

34

The Assignment Operator




The assignment operator is the single equal sign, =. The assignment


operator works in C# much as it does in other computer languages. It
has this general form:

var-name= expression;
 Here, the type of var-name must be compatible with the type of
expression.
 The assignment operator allows you to create a chain of assignments.
For example, consider this fragment:

13.10.2014

35

Compound Assignments


C# provides special compound assignment operators that simplify


the coding of certain assignment statements. Lets begin with an
example. The assignment statement shown here:

can be written using a compound assignment as




The operator pair += tells the compiler to assign to x the value of x


plus 10.
Here is another example. The statement

is the same as

Both statements assign to x the value of x minus 100.

13.10.2014

36

You might also like