lecture 3.1 operators and expressions structured programming instructor: prof. k. t. tsang 1

65
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Upload: brianne-wade

Post on 28-Dec-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Lecture 3.1

Operators and Expressions

Structured ProgrammingInstructor: Prof. K. T. Tsang

1

Page 2: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 3: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 4: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 5: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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*/OrN5 = i3 * 3 + i2 * 5; /*N5=11*/

5

Page 6: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 7: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 8: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 9: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Relational Expressions

Example:a == b; i1 > 34; student_id < 100;

Relational Expressions have values: true or false

10 > 6 true 13 >= 12 false 0-22 == 9 false 0‘A’ != ‘g’ true 1‘M’ > ‘a’ false 0

9

Page 10: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Logical operators

&& and|| or! Not

Example:(n1 < 10) && (n2>= 6)(days > 4) || (months < 7)!(n2 > n1)

10

Page 11: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Truth table

Logical Expressions have truth values.

e1 e2 e1&&e2 e1||e2 !e1

1 1 1 1 0

0 1 0 1 1

1 0 0 1

0 0 0 0

11

Page 12: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Equivalent Expressions

!(a > b) a <= b

!(a < b) a >= b

!(a == b) a != b

a > b !(a <= b)

a < b !(a >= b)

a == b !(a != b)

12

Page 13: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Assignment operators

Simple assignment:

var1 = 10; var2 = i1;

Shorthand assignment:

var1 (op)= exp means

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

Page 14: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 15: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Bit-Operators: & | ^ ~

bit1 bit2 bit1 & bit2 bit1 | bit2 bit1 ^ bit2 ~bit2

0 0 0 0 0 1

0 1 0 1 1 0

1 0 0 1 1

1 1 1 1 0

15

Page 16: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Left and right shift operators

n = 0x1C 00011100

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

Page 17: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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 6th to 4th bits from the right*/

n = n & ~077 /*set the lower 6 bits to 0*/

17

Page 18: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Conditional operator

exp1 ? exp2 : exp3

x = exp1 ? exp2 : exp3

equivalent to

if (exp1) x = exp2;

else x = exp3;

18

Page 19: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Lecture 3.2

Control structures and Loops

Structured ProgrammingInstructor: Prof. K. T. Tsang

19

Page 20: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 21: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Simple IF statement

Expression

Action

true false

Syntaxif(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

Page 22: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 23: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

If…else

if (Expression) Action1 ;

else Action2 ;If the Expression is true

(nonzero), the Action1 will be executed. Otherwise Action2 will be executed.

Expression

Action1 Action2

true false

23

Page 24: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Example: if-else

#include<stdio.h>

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

Page 25: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

25

int getchar ( void );

Get character from stdinReturns the next character from the standard input (stdin).

Use with #include <stdio.h>

The standard library provides several functions for reading one character at a time from the keyboard, of which getchar is the simplest.

Page 26: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 27: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

if-else-if flow-chart

Expression2Action1

Action2

true false

Expression1

Action3

truefalse

27

Page 28: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 29: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 30: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 31: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 32: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

‘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

Page 33: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Nested if Statements

– Nested means that one complete statement is inside another

– Example:

if (<it is Tuesday>) {

if (<it is time for class>) <go to programming class>;

else <meet your friends>;

}

33

Page 34: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

“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

Page 35: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

“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

Page 36: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 37: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

Iterative Constructs

• Provide– Ability to control how many times a statement

list is executed

• Three constructs– while statement– for statement– do-while statement

37

Page 38: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

true false

38

Page 39: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

while loop to calculate 2N

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

Page 40: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 41: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

‘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

Page 42: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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&R42

Page 43: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

for loop to calculate 2N

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

Page 44: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 45: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

45

Page 46: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 47: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

47

K&R p.9

Page 48: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

48

K&R p.15

Page 49: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

The Do-While Statement

• Syntaxdo 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

Page 50: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

“do-while” loop to calculate 2N

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

Page 51: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 52: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 53: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

“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

Page 54: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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

Page 55: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

55

Page 56: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

56

double sum=0.0, product=1.0; int j=0;while (1) {

j++;product = product/double(j);sum= sum + product;if(product < 1.0e-7) break;

}

“break” from a loop

Page 57: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

57

double sum=0.0, prod=1.0; int j, NN=900;for (j=1; j<NN; j++) {

prod= prod/double(j);sum= sum + prod;if(prod < 1.0e-7) break;if(j-j%3 != 0) continue;sum = sum + prod;

}

Effect of the “continue” statement

Page 58: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

58

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 loopiteration.

Page 59: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

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?

59

Page 60: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

60

What’s wrong?

Page 61: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

61

What’s wrong?

Page 62: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

62

Assignment:1.Write a C program to print all prime numbers smaller than a given positive integer N.2.Write a C program to find all prime numbers less than 2^N. Choose any 2 of these prime numbers and find their product. Print out your result. Run the program with N=8.3.Now suppose you are given this product of 2 prime numbers less than 2^N, write another program to determine what these 2 prime numbers are. Is the answer unique? Run the program with N=8.

Page 63: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

63

4. What are the values of i and j after the following lines are executed?int i = 0;int j = 0;int x = 0;i = x++;j = ++x;

Page 64: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

64

5. Consider the following statement:

When state = BEGIN_STATE, what messages will you get?

Page 65: Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1

65

6. Write a program to print the first 50 terms of the Fibonacci Sequence.

The Fibonacci sequence is: 1 1 2 3 5 8 . . .The terms are computed from the equations:112 = 1 + 13 = 1 + 25 = 3 + 2etc.In general terms this is: f n = f n-1 + f n-2