Arithmetic Operations

advertisement

Actions in C code

Operations can be

• arithmetic

• assignment

• relational

• logical

Arithmetic Operations

+, -, *, /

A binary operation → 2 inputs. If both inputs are integers the result is an integer. If not, all numbers are converted to double and the result is type double .

Eg.

int i, j, k; double x, y, j; i=1; j=2; k=3; x=1.1; y=2.2l

z=3.3;

Expression Result i*j i/j k/j i*x x*y

2

0 (ie. the integer part of the result)

1

1.1 (ie. 1.0*1.1)

2.32

Another arithmetic operation is “MODULUS”, written % in C .

int1 % int 2 = remainder when int1 divided by int 2

−→ ONLY FOR POSITIVE INTEGERS. Eg. 5%3 = 2.

A unary operation → 1 input.

Eg. -x ie. -1.1 ; -j ie. -2.

and

++j which is equivalent to writing j=j+1 or --j which is equivalent to writing j=j-1 .

Assignment Operations

Eg.

k = i + j action: i + j is calculated and the result placed at k . If you mix types as in k = y + z , the result of y + z is 5.5 but only the integer part can be stored in k so the value 5 is placed at the memory location k .

Nb .

RHS is done first

Result is assigned to LHS

Relational Operations

numbers in, true/false out

In the processor FALSE = 0 and any bit pattern that is not FALSE is TRUE .

Convention in C is

FALSE = 0

TRUE = 1

See page 7 of the handout for a list of relational operators. Eg. ¡, ¿, ==, !=, ¿=,

¡=. Eg i < j is TRUE = 1 i > j is FALSE = 0 i == j is FALSE = 0 x > i is TRUE = 1

Can make more complicated expressions using parantheses ie (). Eg.

x > ( y + z ).

Whatever is in brackets is done first: y + z = 5 .

5 then x > 5 .

5 is FALSE = 0.

Logical Operators

true/false in, true/false out

&& is logical AND

— — is logical OR

!

is logical NOT

Eg

( x > y )

( F ALSE )

&&

&&

F ALSE = 0

( x < z )

( T RU E )

( x > Y )

( F ALSE )

||

||

T RU E = 1

( x < z )

( T RU E )

For reference the truth table for logical operators is p q && ——

T T T T

T F F T

F T F T

F F F F p !p

T F

F T

Download