C for Engineers and Scientists Chapter 4 Operators

  • Slides: 41
Download presentation
C for Engineers and Scientists Chapter 4: Operators and Expressions Outline Assignment Operator Arithmetic

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists The Assignment Operator • The regular assignment operator ‘=‘.

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 C 99 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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Arithmetic Operators • There are five arithmetic operators: 1)

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 Mc. Graw-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

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Precedence and Associativity of Operators • The list of

C for Engineers and Scientists Precedence and Associativity of Operators • The list of operators are shown on right. Operators at the higher level has precedence over operators at the lower level. Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Precedence and Associativity of Operators Example: the order of

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Note: there is no exponential operator in C. Mathematical

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) = %fn", p); printf("sqrt(2) = %fn", sqrt(x)); return 0; Output: } pow(2, 3) = 8. 000000 sqrt(2) = 1. 414214 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists A Sample Problem A quadratic (second order polynomial) equation

C for Engineers and Scientists A Sample Problem A quadratic (second order polynomial) equation ax 2 + 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 x 2 – 5 x + 6 = 0 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Program 1: Solve for x 2 – 5 x

C for Engineers and Scientists Program 1: Solve for x 2 – 5 x + 6 = 0 /* File: secondorder 1. c */ #include <stdio. h> #include <math. h> int main() { double a = 1. 0, b = -5. 0, c = 6. 0, x 1, x 2; x 1 = (-b +sqrt(b*b-4*a*c))/(2*a); x 2 = (-b -sqrt(b*b-4*a*c))/(2*a); printf("x 1 = %fn", x 1); printf("x 2 = %fn", x 2); return 0; } Output: x 1 = 3. 000000 x 2 = 2. 000000 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Evaluation tree x 1 = ( - b +

C for Engineers and Scientists Evaluation tree x 1 = ( - b + sqrt( b * b – 4 * a * c )) / ( 2 * a) 6 _ 5. 0 1 2 * * 25. 0 4. 0 8 3 * a = 1. 0 b = -5. 0 c = 6. 0 24. 0 4 _ 1. 0 7 + 6. 0 5 sqrt 1. 0 9 3. 0 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved. / x 1 2. 0 *

C for Engineers and Scientists The Law of Sines Created by Harry H. Cheng,

C for Engineers and Scientists The Law of Sines Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Problem: Given the side a =10, alpha = 90

C for Engineers and Scientists Problem: Given the side a =10, alpha = 90 degrees, gamma = 60 degrees. Find the side c. Solution: 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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists /* File: sinelaw. c */ #include <stdio. h> #include

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 = %fn", c); return 0; } Output: c = 8. 660254 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Linear Interpolation Created by Harry H. Cheng, 2009 Mc.

C for Engineers and Scientists Linear Interpolation Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Linear Regression Time and position for a moving body

C for Engineers and Scientists Linear Regression Time and position for a moving body t (seconds) 0 3 5 8 10 12 15 18 y (meters) 2 5. 2 6 10 10. 4 13. 4 14. 8 18 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Interpolation of position at time 11 seconds /* File:

C for Engineers and Scientists Interpolation of position at time 11 seconds /* File: interp. c */ #include <stdio. h> int main() { double t 1, t 2, y 1, y 2, t, y; t 1 = 10. 0; y 1 = 10. 4; t 2 = 12. 0; y 2 = 13. 4; t = 11. 0; y = y 1 + (y 2 -y 1)*(t-t 1)/(t 2 -t 1); /* or y = y 1 + (y 2 -y 1)/(t 2 -t 1)*(t-t 1); */ 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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Relational Operators The relational operators are listed below. Operator

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Examples: > int i = 5, j = 3

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 != i 0 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved. // false // true // false

C for Engineers and Scientists > float f 1 = 0. 2, f 2

C for Engineers and Scientists > float f 1 = 0. 2, f 2 = 0. 3 > printf("%. 20 f", f 1*f 2) 0. 06000000238418579100 > printf("%. 20 f", 0. 06) 0. 0599999999800 > f 1*f 2 == 0. 06 0 For f 1 = 0. 2 and f 2=0. 3, the expression f 1*f 2 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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Logical Operators • There are three logical operators in

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 y !x x && y x || y 0 0 1 0 0 0 1 1 1 0 1 1 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Problem: A given year is a leap year if

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists /* File: leapyear. c Determine if a year input

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 yearn"); 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 Mc. Graw-Hill, Inc. All rights reserved. > leapyear. c Please input a year 2012 is a leap year.

C for Engineers and Scientists Compound Assignment Operators • Besides the regular assignment operator,

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Increment and Decrement Operators – The increment operator ++

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Cast Operators – Used to convert a value of

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 Mc. Graw-Hill, Inc. All rights reserved. // d = 2. 0000/3

C for Engineers and Scientists Sizes of Different Data Types char 1 byte short

C for Engineers and Scientists Sizes of Different Data Types char 1 byte short 2 bytes int 4 bytes 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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Sizeof Operator The sizeof operator can be applied to

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 > 8 > 4 > 4 sizeof (int) sizeof (float) sizeof (double) sizeof (int *) sizeof (float *) sizeof (double *) Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists The operand of sizeof operator can also be a

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Conditional Operator • The execution of a conditional expression

C for Engineers and Scientists Conditional Operator • The execution of a conditional expression op 1 ? op 2 : op 3; • 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(op 1 != 0) r = op 2; else r = op 3; can be reduced to r = op 1 ? op 2 : op 3; Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Example: > 5 ? 1 : 2 1 >

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists ‡ Slides for optional topics in C Created by

C for Engineers and Scientists ‡ Slides for optional topics in C Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Conditional Operator • Conditional expressions are right-associative. For example,

C for Engineers and Scientists Conditional Operator • Conditional expressions are right-associative. For example, op 1 ? op 2 : op 3 ? op 4 : op 5 ? op 6 : op 7 is handled as op 1 ? op 2 : (op 3 ? op 4 : (op 5 ? op 6 : op 7)) 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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists • The first operand of a conditional expression should

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists • Conditional expressions are right-associative. For example, op 1

C for Engineers and Scientists • Conditional expressions are right-associative. For example, op 1 ? op 2 : op 3 ? op 4 : op 5 ? op 6 : op 7 is handled as op 1 ? op 2 : (op 3 ? op 4 : (op 5 ? op 6 : op 7)) Example: > 5 ? 1 : 2 1 > 0 ? 1 : 0 ? 3 : 4 4 > 0 ? 1. 0 : 2 2. 0000 > Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved. // right-association // data type conversion

C for Engineers and Scientists Comma Operator • The comma operator ‘, ’ introduces

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 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists • The comma operator cannot appear in contexts where

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 Mc. Graw-Hill, Inc. All rights reserved. // pow(2, 3) // pow(5, 3)

C for Engineers and Scientists Bitwise Operators • There are six bitwise operators: Operator

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. ~ One’s complement Set all 0 bits to 1, and all 1 bits to 0. Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists Example: a 1 0 1 0 0 b 1

C for Engineers and Scientists Example: a 1 0 1 0 0 b 1 1 0 0 1 a&b 1 0 0 0 0 a|b 1 1 1 0 1 a^b 0 1 1 0 1 b << 1 1 0 0 1 0 a >> 1 1 1 0 1 0 ~a 0 1 0 1 1 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists ‡ Slides for optional topics in Ch Created by

C for Engineers and Scientists ‡ Slides for optional topics in Ch Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.

C for Engineers and Scientists /* File: bitop. ch (run in Ch only) Use

C for Engineers and Scientists /* File: bitop. ch (run in Ch only) Use Ch features “%b” and 0 b */ #include <stdio. h> Output: a = b = a & b = a | b = a ^ b = b << 1 = a >> 1 = ~a = 0 b 10110100 0 b 11011001 0 b 10010000 0 b 11111101 0 b 01101101 0 b 10110010 0 b 11011010 0 b 01001011 int main() { char a = 0 b 10110100; char b = 0 b 11011001; 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 Mc. Graw-Hill, Inc. All rights reserved. 0 b%8 bn", a); 0 b%8 bn", b); 0 b%8 bn", c); 0 b%8 bn", c);

C for Engineers and Scientists Logic Operators • There are four logic operators: 1)

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 b !a a && b a || b a ^^ b 0 0 1 1 0 1 1 1 0 0 0 1 1 0 Created by Harry H. Cheng, 2009 Mc. Graw-Hill, Inc. All rights reserved.