CS计算机代考程序代写 compiler c++ Excel Conditional Execution / Branching

Conditional Execution / Branching

Computer Programming

Conditional statements

2

! So far, all statements we wrote in a C++ program run in sequence
! We can actually ask the program to run (or not to run) a statement

by considering some conditions / criteria set by us.
! It is called “conditional execution” or “branching”
! Syntax:

if () ;

! will be executed only when the is fulfilled
(i.e. is true) otherwise, the statement is skipped as if it does not exist
at all

Conditional statement: Simplest form – if

3

! One or more statements will be executed if the condition is true

………………
if ( logical value / expression)

action for logical value true

………………

! C++ example:

cin >>x;
if (x<0) x=-x; cout << "Absolute value is " <> mark;

if ( mark>=35 )

cout << "You passed!\n"; Note: The condition MUST be enclosed within ( ) If the input mark is greater than or equal to 35, the blue statement is executed. ! If the total mark is 35 or above. It is considered "pass". Otherwise, it is "fail" How to represent the above logic in C++? Two-way selection 5 ! If the condition is true, one ore more statements will be executed. If the condition is false, another set of statement will be executed. ……………… if ( Logical expression) statement2a //action for true else statement2b //action for false ……………… ! C++ example: if (x>=0)
cout << "Positive "; else cout << "Negative "; Some points to note 6 The expression MUST be enclosed by ( ) It is NOT optional! == No semi-colon after if or else If i==3 is true, increment a by 1, otherwise (i==3 is false), decrement a by 1 i == 3 evaluates to a Boolean value The else part is optional Beware of the semi-colon! 7 int x=5; if (x!=5); x=3; cout << x; /*output is 3*/ int x=5; if (x!=5) x=3; cout << x; /*output is 5*/ An empty statement can be specified by a semi-colon ';'. Empty statement specifies that no action should be performed. You may consider it as empty { } For the second program, x is assigned 3 when x is not equals to 5. (Correct!) For the first program, because of the extra semi-colon at the end of the if statement, nothing is executed when x!=5. Meanwhile x=3 is not attached to if and it ALWAYS execute. Compound statement 8 ! Group statements into an executable block with { } ! It is needed if we want to execute two or more statements following the if clause. ! All-or-Nothing: Either all executed or all skipped ! Used for if, else if, and else statement, as well as loops which we’ll go through in the next lecture if (mark>=70){

cout << "You get grade A.\n"; cout << "Excellent!\n"; }  Suggestion: Always use { } even if there’s only one (or zero) statement. It would be easier for future debugging. Examples – Compound statements 9 if (x==3) cout << "x is equal to 3"; if (x>y){
z=x-y;
cout << "x is larger, the different is " << z; }else{ z=y-x; cout << "y is larger, the different is " << z; } Compound statements {…} are treated as one statement Pass or fail? -- Common Mistake 10 int mark; cout << "What is your mark?\n"; cin >> mark;

if (mark>=35){
cout << "You passed!\n"; cout << "Congratulations\n"; } else cout << "You failed!\n"; cout << "You should retake the course\n"; Suppose the user inputs 35. The output: You passed! Congratulations You should retake the course Why? Pass or fail? – Corrected Program 11 int mark; cout << "What is your mark?\n"; cin >> mark;

if (mark>=35){
cout << "You passed!\n"; cout << "Congratulations\n"; } else { cout << "You failed!\n"; cout << "You should retake the course\n"; } Similar to if, else controls just ONE statement. If >1 statements are needed in the else part, let’s
group the statements with brackets

Beyond two way condition…

12

Beyond two way condition…

13

! If you’d like to further sub-divide the “false” part, you may use the
else if () statement, by providing another condition to check

! else if is considered only when the previous if () clause is false

if ( logical value 1) {
statements for logical value is true

}else if (logical value 2){
statements for logical value 1 is false but logical value 2 is true

}else if (…) {

}else{

statements for all the logical values are false
}

14

Logical
Expresson

Statement 2a

Statement 3

Statement 1

Statement 2d

truefalse

Logical
Expresson

Statement 2bLogical
Expresson

Statement 2c

Examples

15

if (x>5){

cout << " x is too large"; } if (x>5)

cout << " x is too large"; else if (x<3) cout << " x is too small"; if (x>5)

cout <<" x is too large"; else if (x<3) cout << " x is too small"; else cout << " x is in range 3..5"; Nested if statement 16 "Nested" means enclosing an if statement inside another if statement if (expression1) if (expression2) statement2a else statement2b statement3 statement1 Dangling else problem 17 ! With which "if" the "else" part is associated? if (a==1) if (b==2) cout << "***\n"; else cout << "###\n"; if (a==1) if (b==2) cout << "***\n"; else cout << "###\n"; ! Actually the 2 pieces of code here are identical Dangling else problem 18 ! C++ ignores spacing and indentation ! An else is ALWAYS attached to the nearest if. if (a==1) if (b==2) cout << "***\n"; else cout << "###\n"; Condition 19 ! The "condition" in brackets is usually an expression, which evaluates to Boolean true or false (e.g. if (a>5) …. )

! It can also be a Boolean variable
(e.g. bool found=true; if ( found ) …. )

! It can actually be an integer as well (rarely used!)
(e.g. int x=5; if ( x ) …. )

! Integer value zero is considered false

! All other integer values (e.g. 1, -1…etc.) are considered true

! So if (x) …. actually means if (x!=0) …..

Comparative Operators

20

! Binary operators which accepts two operands and
compare them

Relational operators Syntax Example
Less than < x z>1
Less than or equal to <= b<=1 Greater than or equal to >= c>=2

Equality operators Syntax Example
Equal to == a==b
Not equal to != b!=3

No space between the 2 ‘=’s !

Do not mix == (equality) and = (assign)

21

Output: “x and y are equal” (and x changed to 1 as a side-effect)
The expression x = y
• Assign the value of y to x (x becomes 1)
• The value of this expression is the value of x, i.e. 1 (which represent true)

• false is represented by 0
• Non-zero represents true

x=0;
y=1;
if (x = y){

cout << "x and y are equal"; } else cout << "unequal"; Common Mistake: Logical Operators 22 ! Used for combining logical values and create new logical values ! Logical AND (&&) ! return true if both operands are true, false otherwise ! Logical OR (||) ! return true if at least one side is true, false otherwise ! Logical NOT (!) ! Invert the Boolean value of the operand ! Don’t write | and &, compiler will not spot that mistake for you! (| and & has a totally different meaning (not taught in this course) It is not syntax error) 23 Original Expression Equivalent to: !(x=y
!(x>y) x<=y !(x!=y) x==y !(x<=y) x>y
!(x>=y) x) is not “smaller” (<), but rather it is "smaller or equals" (<=) 24 The NOT (!) operator: ! Also note that negating an expression means: ! Negating all sub-expression in it, as well as…. ! Changing all AND to OR and vice versa That means: !(a && b) gives (!a || !b) but not (!a && !b) ! For example, consider the criteria of passing a course… ! First, we need condition a: Exam >= 30
! Also we need condition b: Total >= 35
! We can write “passing a course” as fulfilling a AND b, i.e. (a && b)
! Then we consider the “fail” situation, i.e. !(a && b)…
! Fail case happens when a student cannot get 30 in exam (i.e. !a),

OR the total is not 35 or above (i.e. !b)
! Again it turns out that !(a && b) is equivalent to (!a || !b)
! This is known as De Morgan’s Law

Comparing Characters
! Besides numbers we can also compare characters

(e.g. ‘A’ < ‘Z’ is true) ! Characters are compared using their ASCII code ! Therefore ‘A’ (ASCII 65) is smaller than ‘a’ (ASCII 97) ! Not that we cannot compare strings / array directly (e.g. "ABC" < "DEF", or "A"<"D" are SYNTAX ERROR !) ! Example: Check whether x is uppercase / lowercase: If (x>=‘A’ && x<=‘Z’) cout<<"Uppercase\n"; else if (x>=‘a’ && x<=‘z’) cout<<"Lowercase\n"; else cout<<"Not alphabet\n"; Mark to grade conversion (if version) (less efficient) 26 if (mark>=70 && mark<=100) cout << "A"; if (mark>=55 && mark<70) cout << "B"; if (mark>=40 && mark<55) cout << "C"; if (mark>=35 && mark<40) cout << "D"; if (mark<35 && mark>=0)
cout << "F"; if (mark<0 || mark>100)
cout << "Invalid Grade"; Mark to grade conversion (else-if version) (more efficient) 27 if (mark<0 || mark>100)
cout << "Invalid Grade"; else if (mark>=70)
cout << "A"; else if (mark>=55)
cout << "B"; else if (mark>=40)
cout << "C"; else if (mark>=35)
cout << "D"; else cout << "F"; The "else if" or "else" part is executed only if all the preceding conditions are false Mark to grade conversion 28 Common Mistakes: C++ syntax v.s. math syntax 29 if (mark>=70 && mark<=100) …… Can we express the above condition as follows? if (70<=mark<=100) …… Ans: NO, although the above statement is compilable (no syntax error), but the meaning / logic is NOT CORRECT! Similarly, statements like if(a==b==c) is also WRONG! Common Mistakes 30 WRONG! Correct if (a=b) if (a==b) if (a==b==c) if (a==b && b==c) if (a>b>c) if (a>b && b>c)

if (a>b,c) if (a>b && a>c)

if (a=>b) if (a>=b)

if a>b if (a>b)

Summary: Logical/Comparison operators

31

 Relational operators
! less than < ! greater than >
! less than or equal to <= ! greater than or equal to >=

 Equality operators
! equal to ==
! not equal to !=

 Logical operators
! (unary) negation (i.e., not) !
! logical and &&
! logical or ||

Summary: Precedence of operators

32

Operator precedence (high to low) Associativity
() ++(postfix) – (postfix) Left to right
+(unary) -(unary) ++(prefix)– (prefix) Right to left

* / % Left to right
+ – Left to right

< <= > >= Left to right
== != Left to right

&& Left to right
|| Left to right
?: Right to left

= += -= *= /= Right to left
,(comma operator) Left to right

Do you know: Precedence of && and ||
! By default, expressions are evaluated from left to right. Yet things get

complicated since the precedence of && is higher than that of || :
! Example: A || B && C means ?
! Possibility 1 – expression is true when:

! Either A or B is true, and
! C has to be true as well (i.e. (A||B) && C )

! Possibility 2 – expression is true when:
! A is true, or
! B and C are true at the same time (i.e. A|| (B && C) )

! The Answer is 2. B && C, which are connected with && are considered
together. (Just like A+B*C, B*C are considered together)

The morale of the story is: Let’s use parenthesis if you’re not 100% sure!

Partial (short-circuit) evaluation

34

 Evaluation of expressions containing && and || stops as soon as
the outcome true or false is known and this is called partial (short-
circuit) evaluation

 For the case of ||, evaluation stops once a sub-expression is true
(e.g. if (x==1||y==3)… Once x is known to be 1, y is not checked)

 For the case of &&, evaluation stops once a sub-expression is false
(e.g. if (x!=0 && y>10)… Once x is known to be 0, y is not checked)

 Short-circuit evaluation can improve program efficiency

 It can possibly avoid error situation as well
(e.g. if ( b>0 && a/b>5) … skipping a/b avoids “division by zero”)

Advanced Example: Short-circuit evaluation
Let’s try with Visual Studio!

35

 What are the outputs of the following program?

k = (i=2) && (j=2);
cout << i <<" "<< j << endl; //2 2 k = (i=0) && (j=3); cout << i <<" "<< j << endl; //0 2 k = i || (j=4); cout << i <<" "<< j << endl; //0 4 k = (i=2) || (j=5); cout << i <<" "<< j << endl; //2 4 √ √ √ × √ √ √ × Be careful, It’s = but not == switch statement 36  General format of switch statement (selection statement) switch (expression) { case constant-expr1: statement1 case constant-expr2: statement2 ... ... case constant-exprN: statementN default: statement } switch statement (cont’d) 37  Semantics ! Evaluate the switch expression which result in an integer type (e.g. double a=3.14; switch(a){…} is WRONG!) (Trying to apply switch to String (multiple characters) is also WRONG!) ! Go to the case label having a constant value that matches the ! value of the switch expression; if a match is not found, go to the default label; if default label does not exist, terminate the switch ! Terminate the switch when a break statement is encountered ! If there is no break statement, execution "falls through" to the next statement in the succeeding case Example: Print English name of numbers 38 Assume input is in range 1..6 //assume num is 4; switch( num ) { case 1: cout<<"One"; break; case 2: cout<<"Two"; break; case 3: cout<<"Three"; break; case 4: cout<<"Four"; break; case 5: cout<<"Five"; break; case 6: cout<<"Six"; break; default: cout<<"Error, not 1..6"; break; } break; is needed after the statement (cout), otherwise the program "falls through" and also prints "Two","Three" ….etc. default is for cases not qualified for any case above (default is optional) The order of the cases doesn’t matter (if there’s no "fall through") Besides numbers (case 1, case 2…), can also be characters (case ‘A’, case ‘B’..etc) Example: Print Odd/Even (no fall through) !Assume input is in range 1..6 //assume num is 4; switch( num ) { case 1: cout<<"Odd"; break; case 2: cout<<"Even"; break; case 3: cout<<"Odd"; break; case 4: cout<<"Even"; break; case 5: cout<<"Odd"; break; case 6: cout<<"Even"; break; default: cout<<"Error, not 1..6"; break; } Example: Print Odd/Even (use fall through) !Assume input is in range 1..6 //assume num is 4; switch( num ) { case 1: case 3: case 5: cout<<"Odd"; break; case 2: case 4: case 6: cout<<"Even"; break; default: cout<<"Error, not 1..6"; break; } "falls through", as there’s no break in case 4 Talk like an Alien from the C++ planet… conditional (?:) operator 41  General format of ?: operator is expr1 ? expr2 : expr3;  Semantics ! Boolean expression expr1 is evaluated ! If the result is true, then expr2 is taken as result, otherwise expr3 is taken as result. ! Example: ! Find Minimum of x and y: min = (x>y) ? y : x;

(actually it’s identical to: if (x>y) min=y; else min=x; )

! Find absolute value of x: value = (x>0) ? x : -x;
(actually it’s identical to: if (x>0) value=x; else value=-x; )

Checklist

42

After this lecture, students are expected to be able to:
! Make use of if, else and else if for specifying conditions
! Make use of compound statements enclosed by {….}
! Write Boolean expressions with operators like == != > < …etc. ! Join multiple expressions with AND &&, OR || and NOT ! ! Explain the concept of partial evaluation in if() statements ! Make use of switch() statements for decisions with >2 cases
! Explain the need of break; in switch() and the concept of “fall

through”
! Rewrite logical statements from one form to another

(e.g. use if-else to replace switch, use nested if to replace if-else)