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

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Loops. COMP104 Loops / Slide 2 Shortcut Assignment * C++ has a set of operators for applying an operation to a variable and then storing the result back.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
For Loops Programming. COMP102 Prog Fundamentals I: for Loops/Slide 2 The for Statement condition action true false initialization update.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Introduction to C Language
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Chapter 4 Program Control Statements
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
Flow of Control Part 1: Selection
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
C Programming Lecture 6 : Operators Lecture notes : courtesy of Ohio Supercomputing Center, and Prof. Woo and Prof. Chang.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 2 : August 28 webpage:
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Programming Loops (continued).
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Chapter 4 - Program Control
Looping.
Chapter 7 Additional Control Structures
Chapter 4 - Program Control
Miscellaneous Flow Control
3 Control Statements:.
Chapter 6: Repetition Statements
Chapter 4 - Program Control
Chap 7. Advanced Control Statements in Java
Presentation transcript:

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

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

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

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 = i 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

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

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

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

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

Logical operators &&and ||or !Not Example: (n1 = 6) (days > 4) || (months < 7) !(n2 > n1) 10

Truth table Logical Expressions have truth values. e1e2e1&&e2e1||e2!e

Equivalent Expressions !(a > b)a <= b !(a = b !(a == b)a != b a > b!(a <= b) a = b) a == b!(a != b) 12

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

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

Bit-Operators: & | ^ ~ bit1 bit2bit1 & bit2bit1 | bit2bit1 ^ bit2~bit

Left and right shift operators n = 0x1C n << 1 (= 0x38) n >> 2 (= 0x07) “<<“ 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

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

Conditional operator exp1 ? exp2 : exp3 x = exp1 ? exp2 : exp3 equivalent to if (exp1) x = exp2; else x = exp3; 18

Lecture 3.2 Control structures and Loops Structured Programming Instructor: Prof. K. T. Tsang 19

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

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

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

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

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

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

if-else-if flow-chart Expression2 Action 1 Action 2 true false Expression1 Action 3 true false 27

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

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

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

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

‘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

Nested if Statements –Nested means that one complete statement is inside another –Example: if ( ) { if ( ) ; else ; } 33

“ 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

“ 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

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

Iterative Constructs Provide –Ability to control how many times a statement list is executed Three constructs –while statement –for statement –do-while statement 37

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

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

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

‘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

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

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

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

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 K&R p.9

48 K&R p.15

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

“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

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

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

“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

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

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

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

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 loop iteration.

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

60 What’s wrong?

61 What’s wrong?

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.

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;

64 5. Consider the following statement: When state = BEGIN_STATE, what messages will you get?

65 6. Write a program to print the first 50 terms of the Fibonacci Sequence. The Fibonacci sequence is: The terms are computed from the equations: 1 2 = = = etc. In general terms this is: f n = f n-1 + f n-2