Download presentation
Presentation is loading. Please wait.
Published byAlexander Williams Modified over 8 years ago
1
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1
2
Binary Arithmetic Operators (p.41) Binary arithmetic operators: +, -, *, / (float, double, or mixed) % modulus operator (for integer only) int i1=9, i2=4, i3=6, i4, i5; i4=i1/i2; i5=(i1+i2)*i3/i4;/*int division results int*/ printf( “The answer is %d\n”, i5); float f1=4.5, f2=2.3; float f3 = f1/f2;/*float division results float*/ f3 = 15/10.0;/*mixed mode results f3=1.5*/ f3 = 15/10;/*int division first then cast into float f3=1.0*/ f3 = 13 % 5;/*answer: 3 remainder*/ 2
3
Type Casting 强制性类型转换 int i2 = 5; float x2; x2 = (float)i2 / 4.0; In general, explicit type conversion can be forced by a unary operator called a cast. (type-name) expression 3
4
Unary Arithmetic Operators ++-- int i1=0, N1, N2; i1++;/*postfix—increment by 1 after value is used*/ ++i1;/*prefix—increment by 1 before value is used */ int i8=9; i8--; /*postfix—decrement by 1 after value is used */ --i8; /*prefix—decrement by 1 before value is used */ i1 = 5; N1 = i1++;/i1=6, N1=5*/ i1 = 5; N2 = ++i1;/i1=6, N2=6*/ 4
5
Examples of ++ and -- /*Any difference between the following Expressions?*/ int i1=0, i8=9, N1, N2, N3, N4, N5; N1 = i1++ + i8--; /*i1=1, i8=8, N1=9*/ N2 = i1++ + --i8; /*i1=2, i8=7, N2=8*/ N3 = ++i1 + i8--;/*i1=3, i8=6, N3=10*/ N4 = ++i1 + --i8;/*i1=4, i8=5, N4=9*/ /*What is this?? Never write code like this*/ i1 = 1; N5 = i1++ * 3 + i1++ * 5; /*Result is compiler dependent*/ /*Do this instead*/ i2 = i1++;/*i2=1, i1=2*/ i3 = i1++;/*i3=2, i1=3*/ N5 = i2 * 3 + i3 * 5;/*N5=13*/ Or N5 = i3 * 3 + i2 * 5;/*N5=11*/ 5
6
Post-fixing & Pre-fixing ++/-- Post-fixing ++/-- a variable in an expression, the expression is evaluated first with the original value of the variable before it is incremented or decremented by 1. Pre-fixing ++/-- a variable in an expression, it is incremented or decremented by 1 first before the expression is evaluated with the new value of the variable. 6
7
Precedence and Associativity of operators ( p.53 K&R ) Precedence – which operation to be performed first? n1 + n2 * n3 - ++n4 / n5 Same as n1 + (n2 * n3) – ((++n4) / n5) Associativity – order of operations with same precedence when there is no parenthesis n1 * n2 / n3 means (n1 * n2) / n3--left to right-- To avoid confusion, always use parentheses. 7
8
Relational operators To form relational Expression to be used in control Actions. ( p.41 K&R) Larger than> Larger than or equal to>= Less than< Less than or equal to<= Equal to== Not equal to!= 8
9
Relational Expressions Example: a == b; i1 > 34; student_id < 100; Relational Expressions have values: true or false 10 > 6true1 3 >= 12false0 -22 == 9false0 ‘A’ != ‘g’true1 ‘M’ > ‘a’false0 9
10
Logical operators &&and ||or !Not Example: (n1 = 6) (days > 4) || (months < 7) !(n2 > n1) 10
11
Truth table Logical Expressions have truth values. e1e2e1&&e2e1||e2!e1 11110 01011 1001 0000 11
12
Equivalent Expressions !(a > b)a <= b !(a = b !(a == b)a != b a > b!(a <= b) a = b) a == b!(a != b) 12
13
Assignment operators Simple assignment: var1 = 10; var2 = i1; Shorthand assignment: var1 (op)= expmeans var1 = var1 (op) exp Examples: a += 5;/* a = a + 5 */ a -= n;/* a = a – n */ x *= a + b;/* x = x * (a + b) */ x /= 16;/* x = x / 16 */ x %= 2;/* x = x % 2 */ 13
14
Bitwise operators (p. 48 K&R) Six operators for bit manipulation, applied only to char, short, int, long (signed or unsigned). &bitwise AND |bitwise inclusive OR ^bitwise exclusive OR <<left shift >>right shift ~complement (unary) 14
15
Bit-Operators: & | ^ ~ bit1 bit2bit1 & bit2bit1 | bit2bit1 ^ bit2~bit2 0 00001 0 10110 1 0011 1 1110 15
16
Left and right shift operators n = 0x1C00011100 n << 1 (= 0x38)00111000 n >> 2 (= 0x07)00000111 “<<“ moves data left fixed number of bits. New bits come from right are zeros. “>>” moves data right fixed number of bits. New bits come from left are zeros 16
17
Examples n = n & 0177;/*set all but lower 7 bits to 0*/ n = n & 0377; /*set all but lower 8 bits to 0*/ n = n | 070; /*set to 1 the 6 th to 4 th bits from the right*/ n = n & ~077/*set the lower 6 bits to 0*/ 17
18
Conditional operator exp1 ? exp2 : exp3 x = exp1 ? exp2 : exp3 equivalent to if (exp1) x = exp2; else x = exp3; 18
19
Lecture 3.2 Control structures and Loops Structured Programming Instructor: Prof. K. T. Tsang 19
20
Control structures Provide –Ability to control whether an Action list is executed Two constructs –if statement if if-else if-else-if –switch statement 20
21
Simple IF statement Expression Action truefalse Syntax if(Expression) Action; If the Expression is true (nonzero), the action will be executed. Otherwise do nothing. Example: if ( n1 > n2 ) printf( “%d is larger than %d\n”, n1, n2); 21
22
If…else statement Example: int n1 = 23; int n2 = 35; if ( n1 > n2 ) printf( “%d is larger than %d\n”, n1, n2); else printf( “%d is not larger than %d\n”, n1, n2); 22
23
If…else if (Expression) Action1 ; else Action2 ; If the Expression is true (nonzero), the Action1 will be executed. Otherwise Action2 will be executed. Expression Action 1 Action 2 true false 23
24
Example: if-else #include int main() { int value1; int value2; int larger; printf("Enter two characters:\n” ); if(value1 = getchar() == EOF ) return (0); if(value2 = getchar() == EOF ) return (0); if(value1 > value2) larger = value1; else larger = value2; printf( "Larger of the inputs in ASCII is: %c\n“, larger) ; return (0); } 24
25
25 int getchar ( void ); Get character from stdin Returns the next character from the standard input (stdin). Use with #include The standard library provides several functions for reading one character at a time from the keyboard, of which getchar is the simplest.
26
if-else-if statement General form (p. 23): if ( Expression_1 ) Action_1 ; else if ( Expression_2 ) Action_2 ; … else if ( Expression_n ) Action_n ; else Action_m ; 26
27
if-else-if flow-chart Expression2 Action 1 Action 2 true false Expression1 Action 3 true false 27
28
Example: if-else-if int score;... if(score >= 90) printf( "Grade = A\n“ ); else if(score >= 80) printf( "Grade = B\n“ ); else if(score >= 70) printf( "Grade = C\n“ ); else if(score >= 60) printf( "Grade = D\n“ ); else printf( "Grade = E\n“ ); 28
29
Switch statement – When there are too many ‘else-if’s it is easier to use a switch block. int score;... switch(score/10){ case 10: printf( "Grade = A\n”); break; case 9: printf( "Grade = A\n”); break; case 8: printf( "Grade = B\n”); break; case 7: printf( "Grade = C\n”); break; case 6: printf( "Grade = D\n”); break; default: printf( "Grade = E\n”); } 29
30
Switch statement: effect of ‘break’ int score;... switch(score/10){ case 10: /*no action, falls through*/ case 9: printf( "Grade = A\n”); break; case 8: printf( "Grade = B\n”); break; case 7: printf( "Grade = C\n”); break; case 6: printf( "Grade = D\n”); break; default: printf( "Grade = E\n”); } 30
31
More example: ‘switch’ statement int left; int right; char oper; printf( "Enter simple Expression: \n“); cin >> left >> oper >> right; cout << left << " " << oper << " " << right << " = "; switch (oper) { case '+' : cout << left + right << endl; break; case '-' : cout << left - right << endl; break; case '*' : cout << left * right << endl; break; case '/' : cout << left / right << endl; break; default: cout << "Illegal operation" << endl; } 31
32
‘break’ statement – cause the program action break out from the block Loops or switch statement can be exited at any point through the use of a break statement. Example: int c; while (1) {/*infinite loop*/ if (c=getchar() == EOF) break; printf(“you have enter %c\n”, c); } 32
33
Nested if Statements –Nested means that one complete statement is inside another –Example: if ( ) { if ( ) ; else ; } 33
34
“ Dangling Else ” Problem Problem: Nested if statements can seem ambiguous in their meaning. What is the value of c after the following is executed? int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else c = 3; 34
35
“ Dangling Else ” Problem C groups a dangling else with the most recent if. The following indentation shows how C/C++ would group this example (answer: c=1 ). int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else // dangling else grouped to nearest if c = 3; 35
36
Use braces to clear up ambiguity int a=-1, b=1, c=1; if(a>0){ if(b>0) c = 2; } else c = 3; Or int a=-1, b=1, c=1; if(a>0){ if(b>0) c = 2; else c = 3; } 36
37
Iterative Constructs Provide –Ability to control how many times a statement list is executed Three constructs –while statement –for statement –do-while statement 37
38
while loop Syntax: while (condition) Action; Or: while (condition) { Action1; Action2; Action3; … } Example: p. 9 & p.12 K&R ( What is the difference?) Condition Action truefalse 38
39
while loop to calculate 2 N int number, result, n; result = 1; n = 1; number = 6; while (n <= number) { result *= 2; n++; } printf("Two raised to the %d power is %d\n“, number, result); 39
40
while loop to calculate N! int number, factorial, n; number = 8; factorial = 1; n = 1; while (n <= number) { factorial *= n; n++; } printf(" The factorial of %d is %d\n“, number, factorial); 40
41
‘break’ statement – cause the program action break out from the block Loops or switch statement can be exited at any point through the use of a break statement. Example: int c; while (1) {/*infinite loop*/ if (c=getchar() == EOF) break; printf(“you have enter %c\n”, c); } 41
42
for loop for (initial-Action; condition; iteration-Action) body-Action; Equivalent to: initial-Action; while (condition) { body-Action; iteration-Action; ) Example: p.13 & p.15 K&R 42
43
for loop to calculate 2 N int number, result, n; result = 1; n = 1;/*iteration variable*/ number = 6;/*or other ways to input number*/ if (number == 0) printf("Two raised to 0 power is %d\n“, result); else { for(n=1; n<=number; n++) result *= 2; printf("Two raised to the %d power is %d\n“, number, result); } 43
44
for loop to calculate N! int number, result, n; result = 1; n = 1;/*iteration variable*/ number = 6;/*or other ways to input number*/ if (number == 0) printf(" The factorial of 0 is %d\n“, result); else { for(n=1; n<=number; n++) result *= n; printf(" The factorial of %d is %d\n“, number, result); } 44
45
45
46
Exercise/study examples K&R p. 9: print Fahrenheit – Celsius table p. 19: line counting p. 20: word counting p. 22: number of occurrence (after we learn ‘arrays’) 46
47
47 K&R p.9
48
48 K&R p.15
49
The Do-While Statement Syntax do Action while (Expression) How it works: –Execute Action –if Expression is true then execute Action again –Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action true false Expression 49
50
“do-while” loop to calculate 2 N int number, result, n; result = 1; n = 1;/*iteration variable*/ number = 6;/*or other ways to input number*/ if (number == 0) printf("Two raised to 0 power is %d\n“, result); else { do { result *= 2; n++; } while(n <= number); printf("Two raised to the %d power is %d\n“, number, result); } 50
51
Which Loop to Use? ‘for’ loop –Usually best for sums, products, and counting. ‘while’ loop –You want to repeat an action without knowing exactly how many times it will be repeated. –You are working with user input –There are situations when the action should not be executed. ‘do-while’ loop –The action should always be executed at least once. –Otherwise, the do-while loops and while loops are used in similar situations. 51
52
Key Points of Iteration –Make sure there is a statement that will eventually stop the loop –Make sure to initialize loop counters correctly –Be sure to initialize to 0 a variable used for sums –Be sure to initialize to 1 a variable used for products –Have a clear purpose for the loop 52
53
“do-while” loop to calculate N! int number, result, n; result = 1; n = 1;/*iteration variable*/ number = 6;/*or other ways to input number*/ if (number == 0) printf(" The factorial of 0 is %d\n“, result); else { do { result *= n; n++; } while (n <= number); printf(" The factorial of %d is %d\n“, number, result); } 53
54
How to Stop a Loop Known number of iterations before the loop stops (for) Carefully test for a user-controlled condition before or after each iteration (while, do-while) 54
55
55
56
56 The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step. The continue statement applies only to loops, not to switch. A continue inside a switch inside a loop causes the next loop iteration.
57
Common Loop Errors float balance=100.0, amount=0.01; while (balance != 0.0) { balance = balance - amount; } –This will lead to an infinite loop! balance may not become equal zero due to numerical inaccuracies. int n, count = 10; for (n=1; n<=count; n++); { printf( "hello\n“); } –"hello" only printed once! Why? 57
58
58 What’s wrong?
59
59 What’s wrong?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.