Вы находитесь на странице: 1из 41

C for Engineers and Scientists

Chapter 4: Operators and Expressions


Outline
Assignment Operator
Arithmetic Operators
Precedence and Associativity of Operators
Relational Operators
Logic Operators
Compound Assignment Operators
Increment and Decrement Operators
Cast Operators
The sizeof Operator
Conditional Operator
Comma Operator
Bitwise Operators
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

The Assignment Operator


The regular assignment operator =.
When a floating-point number is assigned to an integer variable, the
fractional part will be discarded.
One may round a positive floating-point number by adding 0.5 to it.
One may round a negative floating-point number by subtracting 0.5 from
it.
function round() in C99 can be used for rounding a floating-point number.
> int i
> double d = 10.789
> i = d
10
> i = d + 0.5
11
> i = round(d)
11
> i = round(-d)
-11
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Arithmetic Operators
There are five arithmetic operators:
1)
2)
3)
4)
5)

+
*
/
%

Addition
Subtraction
Multiplication
Division
Modulus

The multiplication operator * is needed for multiplication.


The result of the % operator is the remainder. If the value of
the second operand is zero, the behavior is undefined.
The operands of the % operator shall have integer type.
Example:

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

> int i = 10
> 5*i
50
> 19/5
3
> 19.0/5
3.8000
> 19/5.0
3.8000
> 19%5
4

C for Engineers and Scientists

A data type that occupies less memory can be converted to a data type that occupies
more memory space without loss of any information.
The order of real numbers ranges from char, short, int, float, double, to long double.
The algorithms and resultant data types of operations depend on the data types of the
operand.
For binary operations, such as addition, subtraction, multiplication, and division, the
resultant data type will take the higher order data type of two operands.
For example, the addition of two float numbers will result in a float, while the addition
of a float and a double will result in a double.

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Precedence and Associativity of Operators


Operations

The list of operators


are shown on right.
Operators at the
higher level has
precedence over
operators at the
lower level.

Associativity

::
() []

left to right

Function_name()

right to left

. ->

left to right

! ` ++ -- + - *
&(type) sizeof

right to left

* / % .* ./

left to right

+ -

left to right

<< >>

left to right

< <= > >=

left to right

== !=

left to right

&

left to right

left to right

left to right

&&

left to right

^^

left to right

||

left to right

?:

right to left

= += -= *= /= %= |=
<<= >>=

right to left

left to right

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Precedence and Associativity of Operators


Example: the order of the precedence for operators *, +, and =.
Operator * is the highest, operator = the lowest in the expression i = 2 + 3 *4

> int i
> i = 2+3*4
14

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Note: there is no exponential operator in C. Mathematical


function pow(x, y) can be used to calculate the exponential
expression xy. These functions are declared inside the header
file math.h
Example:

/* File: powsqrt.c */
#include <stdio.h>
#include <math.h> /* for pow() and sqrt() */
int main() {
double p, x = 2.0, y = 3.0;
p = pow(x,y);
printf("pow(2,3) = %f\n", p);

printf("sqrt(2) = %f\n", sqrt(x));


return 0;
}

Output:

pow(2,3) = 8.000000
sqrt(2) = 1.414214

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

A Sample Problem
A quadratic (second order polynomial) equation
ax2 + bx + c = 0

can be solved by the formulas

Note: The square root of a negative value is a complex number.


If the result is constrained in the real domain, the value is Not-a-Number.
Write a program to solve for x in equation x2 5x + 6 = 0

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Program1: Solve for x2 5x + 6 = 0


/* File: secondorder1.c */
#include <stdio.h>
#include <math.h>
int main() {
double a = 1.0, b = -5.0, c = 6.0, x1, x2;
x1 = (-b +sqrt(b*b-4*a*c))/(2*a);
x2 = (-b -sqrt(b*b-4*a*c))/(2*a);
printf("x1 = %f\n", x1);
printf("x2 = %f\n", x2);
return 0;
}

Output:
x1 = 3.000000
x2 = 2.000000

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Evaluation tree
x1 = ( - b + sqrt( b * b 4 * a * c )) / ( 2 * a)
6

5.0

25.0

4.0

*
a = 1.0
b = -5.0
c = 6.0

24.0

_
1.0
7

+
6.0

sqrt
1.0
9

3.0
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

x1

2.0

C for Engineers and Scientists

The Law of Sines

a
b
c

sin( ) sin( ) sin( )


Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Problem:
Given the side a =10, alpha = 90 degrees, gamma = 60 degrees.
Find the side c.

Solution:

a sin( )
c
sin( )

Trigonometric functions such as sin(x), cos(x), tan(x) for sine, cosine,


and tangent are declared in the header file math.h . These functions
return a value of double type. The unit for the argument of trigonometric
functions is in radian, not in degree. is defined as M_PI in header
file math.h in most systems. If not, define it by
#define M_PI

3.14159265358979323846

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

/* File: sinelaw.c */
#include <stdio.h>
#include <math.h> /* for sin() and M_PI */
int main() {
double a, c, alpha, gamma;
a = 10.0;
/* side a */
alpha = 90.0*M_PI/180; /* change 90 degrees into radian */
gamma = 60.0*M_PI/180; /* change 60 degrees into radian */
c = a*sin(gamma)/sin(alpha);/* use sine law to compute c */
printf("c = %f\n", c);
return 0;
}

Output:

c = 8.660254

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Linear Interpolation

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Linear Regression
Time and position for a moving body
t (seconds)

10

12

15

18

y (meters)

5.2

10

10.4

13.4

14.8

18

18
16
14

y (meters)

12
10
8
6
4
2
0

8
10
t (seconds)

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

12

14

16

18

C for Engineers and Scientists

Interpolation of position at time 11 seconds


/* File: interp.c */
#include <stdio.h>
int main() {
double t1, t2, y1, y2, t, y;
t1 = 10.0;
y1 = 10.4;
t2 = 12.0;
y2 = 13.4;
t = 11.0;
y = y1 + (y2-y1)*(t-t1)/(t2-t1);
/* or y = y1 + (y2-y1)/(t2-t1)*(t-t1); */
printf("y = %f(m) at t = %f (second)\n", y, t);
return 0;
}

Output:

y = 11.900000(m) at t = 11.000000 (second)

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Relational Operators
The relational operators are listed below.
Operator
<

Description
less than comparison

<=

less or equal comparison

==

equal comparison

>=

greater or equal comparison

>

greater comparison

!=

not equal comparison

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Examples:

> int i = 5, j = 3
>i<j
0
> i <= j
0
> i == j
0
> j == j
1
>i>j
1
> i >= j
1
> i != j
1
> i != i
0

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

// false
// false
// false
// true
// true
// true
// true
// false

C for Engineers and Scientists

> float f1 = 0.2, f2 = 0.3


> printf("%.20f", f1*f2)
0.06000000238418579100
> printf("%.20f", 0.06)
0.05999999999999999800
> f1*f2 == 0.06
0

For f1 = 0.2 and f2=0.3, the expression f1*f2 does not equal to 0.6.
Due to accumulation of the relative errors of expressions, when comparing
the equivalence of two floating-point numbers x and y with data types
float or double, we usually do not use the equal comparison operator = =,
instead, the absolute value of the difference of these two numbers are
evaluated and compared with a small number, such as machine epsilon.
#include <math.h> // for using function fabs()
#include <float.h> // for using FLT_EPSILON
double x, y;
...
if(fabs(x-y) < FLT_EPSILON) {
/* x equals y or x is very close to y */
}
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Logical Operators
There are three logical operators in C:
1) !
--- logical negation
2) && --- logical AND
3) ||
--- local inclusive OR

!x

x && y

x || y

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Problem:
A given year is a leap year if one of the following two conditions are satisfied:
(a) if it divides exactly by four, but cannot be divided exactly by 100 or (b) if
it divides exactly by 400. For example, 2000 is a leap year because it divides
exactly by 400.Write a program to determine if a given year read from the
user input is a leap year or not.

Solution:
The expression
year%4 == 0 && year%100 != 0 || year%400 == 0

evaluates to 1 if either condition (a) or (b) is true.

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

/* File: leapyear.c
Determine if a year input from the terminal is a leap year */
#include <stdio.h>
int main() {
int year; /* year (input from the user) */
/* prompt the user for input */
printf("Please input a year\n");
scanf("%d", &year);

if(year%4 == 0 && year%100 != 0 || year%400 == 0)


printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
return 0;
}

Execution:

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

> leapyear.c
Please input a year
2012
2012 is a leap year.

C for Engineers and Scientists

Compound Assignment Operators

Besides the regular assignment operator, there are ten additional compound assignment
operators:
1) +=
2) -=
3) *=
4) /=
5) %=
6) &=
7) |=
8) ^=
9) <<=
10) >>=

An lvalue is any object that occurs on the left hand side of an assignment statement. It
refers to a memory such as a variable or pointer, not a function or constant.
The expression lvalue op= rvalue is defined as lvalue = lvalue op rvalue, where lvalue
is any valid lvalue.
For example,
i += 3;
is equivalent to
i = i+3;

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Increment and Decrement Operators


The increment operator ++ adds 1 to its operand, and the decrement
operator - - subtracts 1.
If either is used as a prefix operator, the expression increments or
decrements the operand before its value is used.
If either is used as a postfix operator, the increment and decrement
operation will be performed after its value has been used.
Example:
i = 5;
i++;
j = ++i;
j = i++;

// i = i+1 i becomes 6
// i = i+1; j = i; i becomes 7 and j is 7
// j = i; i = i+1; j is 7 and i becomes 8

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Cast Operators
Used to convert a value of one type explicitly to a value of another type.
C cast operation
(type)expr;
where expr is an expression and type is a data type of a single object such as
char, int, float, double, or and pointer declaration such as char *.

Example:

> int i = 2, j = 3
> double d
> i/j
0
> 2/3
0
> d = (double)i/j
0.6667
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

// d = 2.0000/3

C for Engineers and Scientists

Sizes of Different Data Types


char

1 byte

short

2 bytes

int

4 bytes

long long

8 bytes

float

4 bytes

double

8 bytes

pointer type

4 bytes for 32-bit machines


8 bytes for 64-bit machines

pointer to char

4 bytes

pointer to double

4 bytes

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Sizeof Operator
The sizeof operator can be applied to any data type to determine the
number of bytes required to store that particular data type in memory. For
example, for 32-bit machines,
>
4
>
4
>
8
>
4
>
4
>
4

sizeof (int)
sizeof (float)
sizeof (double)
sizeof (int *)
sizeof (float *)
sizeof (double *)

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

The operand of sizeof operator can also be a variable or


expression. For example,
> int i
> sizeof (i)
4
> sizeof(5.0*i)
8

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Conditional Operator

The execution of a conditional expression


op1 ? op2 : op3;

proceeds as follows:
1. The first operand of scalar type is evaluated.
2. The second operand is evaluated only if the first does not evaluate to 0.
The third operand is evaluated only if the first evaluates to 0.
3. The result is the value of the second or third operand, whichever is
evaluated.
Using the conditional operator ?:, the following conditional expression
if(op1 != 0)
r = op2;
else
r = op3;

can be reduced to
r = op1 ? op2 : op3;

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Example:
> 5 ? 1 : 2
1
> int x = 2
> x>5 ? 1.0 : 2
// data type conversion
2.0000
> double y
> y = x>5 ? 1.0 : 2
2.0000

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Slides

for optional topics in C

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Conditional Operator

Conditional expressions are right-associative. For example,


op1 ? op2 : op3 ? op4 : op5 ? op6 : op7

is handled as
op1 ? op2 : (op3 ? op4 : (op5 ? op6 : op7))

Example:
> int x = 2
1
> x>5 ? 1 : x<1 ? 3 : 4
// right-association
4
> (x>5) ? 1 : (x<1 ? 3 : 4)
4

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

The first operand of a conditional expression should be a scalar type.


For the second and third operand, one of the following shall hold:
1. Both operands have arithmetic type.
2. Both operands have compatible class, structure, or union
types.
3. Both operands have void type.
4. Both operands are pointers to compatible types.
5. One operand is a pointer and the other is NULL.
6. One operand is a pointer to an object or incomplete type and
the other is a pointer to void.
7. Both operands are computational arrays of the same shape.

If the data types of the second and third operands are different, the data
type of the result takes the higher order of the two operands. For
example, the result of expression expr?double_expr:int_expr has the
data type of double.
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Conditional expressions are right-associative. For example,


op1 ? op2 : op3 ? op4 : op5 ? op6 : op7

is handled as
op1 ? op2 : (op3 ? op4 : (op5 ? op6 : op7))

Example:
> 5 ? 1 : 2
1
> 0 ? 1 : 0 ? 3 : 4
4
> 0 ? 1.0 : 2
2.0000
>

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

// right-association
// data type conversion

C for Engineers and Scientists

Comma Operator
The comma operator , introduces comma expression.
The comma expression consists of two expressions separated by a
comma. For example,
a = 1, b=2;
This is useful for a for-loop to be described in next chapter.
The comma operator is syntactically left-associative. The following
expression
a = 1, ++a, a + 10;
is equivalent to
((a = 1), ++a), a + 10;
The left operand of a comma operator is evaluated as a void expression
first. Then the right operand is evaluated; the result has its type and
value. For example,
> a = 1, ++a, a + 10
12
>a
2
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

The comma operator cannot appear in contexts where a comma is used as a


separate item such as the argument list of a function. In these cases, it can be
used within parenthesis.

For example, the exponential function pow(x,y) defined in the header file
math.h for the mathematical expression xy has two arguments. It can be
evaluated as shown below.
> double x= 2, y = 3
> pow(x,y)
8.0000
> pow((x=2, x+3), y)
125.0000

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

// pow(2,3)
// pow(5,3)

C for Engineers and Scientists

Bitwise Operators

There are six bitwise operators:

Operator

Name

Description

&

bitwise AND

The bit is set to 1 if the corresponding bits in the


two operands are both 1.

bitwise OR

The bit is set to 1 if at least one of the


corresponding bits in the two operands is 1.

bitwise exclusive OR

The bit is set to 1 if exactly one of the


corresponding bits in the two operands is 1.

<<

left shift

Shift the bits of the first operand left by the number


of bits specified by the second operand; fill from
right with 0 bits.

>>

right shift

Shift the bits of the first operand right by the


number of bits specified by the second operand;
filling from the left is implementation dependent.

Ones complement

Set all 0 bits to 1, and all 1 bits to 0.

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Example:
a

1 0 1 1 0 1 0 0

1 1 0 1 1 0 0 1

a&b

1 0 0 1 0 0 0 0

a|b

1 1 1 1 1 1 0 1

a^b

0 1 1 0 1 1 0 1

b << 1

1 0 1 1 0 0 1 0

a >> 1

1 1 0 1 1 0 1 0

~a

0 1 0 0 1 0 1 1

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

Slides

for optional topics in Ch

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists

/* File: bitop.ch (run in Ch only)


Use Ch features %b and 0b */
#include <stdio.h>

Output:
a =
b =
a & b =
a | b =
a ^ b =
b << 1 =
a >> 1 =
~a =

0b10110100
0b11011001
0b10010000
0b11111101
0b01101101
0b10110010
0b11011010
0b01001011

int main() {
char a = 0b10110100;
char b = 0b11011001;
char c;
printf("a =
printf("b =
c = a & b;
printf("a & b =
c = a | b;
printf("a | b =
c = a ^ b;
printf("a ^ b =
c = b << 1;
printf("b << 1 =
c = a >> 1;
printf("a >> 1 =
c = ~a;
printf("~a =
return 0;
}

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

0b%8b\n", a);
0b%8b\n", b);
0b%8b\n", c);

0b%8b\n", c);
0b%8b\n", c);
0b%8b\n", c);
0b%8b\n", c);
0b%8b\n", c);

C for Engineers and Scientists

Logic Operators

There are four logic operators:


1) !
--- logic NOT
2) && --- logic AND
3) ||
--- inclusive OR
4) ^^
--- exclusive OR (available in Ch only)

!a

a && b

a || b

a ^^ b

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

Вам также может понравиться