Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Conditions, Logical Expressions, and Selection Control Structures.

Similar presentations


Presentation on theme: "1 Conditions, Logical Expressions, and Selection Control Structures."— Presentation transcript:

1 1 Conditions, Logical Expressions, and Selection Control Structures

2 2 Topics l Using Relational and Logical Operators to Construct and Evaluate Logical Expressions l If-Then-Else Statements l If-Then Statements l Nested If Statements for Multi-way Branching

3 3 Flow of Control l the order in which program statements are executed WHAT ARE THE POSSIBILITIES...

4 4 Flow of Control l is Sequential unless a “control structure” is used to change that l there are 2 general types of control structures: Selection (also called branching) Repetition (also called looping)

5 5 C++ control structures l Selection if if... else l Repetition for loop while loop do... while loop

6 6 Control Structures use logical expressions which may include: 6 Relational Operators < <= > >= === !== 3 Logical Operators !&&||

7 7 === vs == The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal. Reference: Javascript Tutorial: Comparison OperatorsJavascript Tutorial: Comparison Operators The == operator will compare for equality after doing any necessary type conversions. The ===operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same. To quote Douglas Crockford's excellent JavaScript: The Good Parts,JavaScript: The Good Parts JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases: '' == '0' // false 0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true ' \t\r\n ' == 0 // true The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use ===and !==. All of the comparisons just shown produce false with the === operator.

8 8 are used in expressions of form: ExpressionA Operator ExpressionB temperature > humidity B * B - 4.0 * A * C > 0.0 abs (number ) === 35 initial ! == ‘Q’ 6 Relational Operators

9 9 var x, y ; x = 4; y = 6; EXPRESSIONVALUE x < y true x + 2 < y false x !== y true x + 3 >= y true y === x false y === x+2 true

10 IF / ELSE Statement

11 11 if ( Expression ) { StatementA } else { StatementB } NOTE: StatementA and StatementB each can be a single statement, a null statement, or a block. If-Then-Else Syntax

12 12 if... else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE if clauseelse clause expression

13 13 if ( i < 0 ) { println( i + “ is negative”); } else { println( i + “ is non-negative”); } If-Then-Else Example

14 14 Use of blocks required if ( Expression ) { } else{ } “if clause” “else clause”

15 15 If-Then-Else for a mail order Assign value.25 to discountRate and assign value 10.00 to shipCost if purchase is over 100.00 Otherwise, assign value.15 to discountRate and assign value 5.00 to shipCost Either way, calculate totalBill

16 16 Solution if ( purchase > 100.00 ) { discountRate = 0.25 ; shipCost = 10.00 ; } else { discountRate =.15 ; shipCost = 5.00 ; } totalBill = purchase * (1.0 - discountRate) + shipCost ;

17 IF / THEN Statement

18 18 If-Then statement is a selection of whether or not to execute a statement (which can be a single statement or an entire block) TRUE FALSE statement expression

19 19 if ( Expression ) { Statement } If-Then Syntax

20 20 Write If-Then or If-Then-Else for each If taxCode is ‘T’, increase price by adding taxRate times price to it. If code has value 1, calculate and display taxDue as their product. If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A.

21 21 Some Answers if (taxCode === ‘T’) { price = price + taxRate * price ; } if ( code === 1) { taxDue = income * taxRate; println( taxDue); }

22 22 Remaining Answer if ( ( A > 0 ) && (A < 5) ) { B = 1/A; } else { B = A; }

23 23 Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection statement.

24 Nested IF Statements

25 25 Multi-alternative Selection is also called multi-way branching, and can be accomplished by using NESTED if statements.

26 26 if ( Expression1 ) { Statement1 } else if ( Expression2 ) { Statement2 }. else if ( ExpressionN ) { StatementN } else { Statement N+1 } EXACTLY 1 of these statements will be executed. Nested if Statements

27 27 Nested if Statements Each Expression is evaluated in sequence, until some Expression is found that is true. Only the specific Statement following that particular true Expression is executed. If no Expression is true, the Statement following the final else is executed. Actually, the final else and final Statement are optional. If omitted, and no Expression is true, then no Statement is executed.

28 28 if ( creditsEarned >= 90 ) { println(“SENIOR STATUS “); } else if ( creditsEarned >= 60 ) { println(“JUNIOR STATUS “); } else if ( creditsEarned >= 30 ) { println(“SOPHOMORE STATUS “); } else { println(“FRESHMAN STATUS “); } Multi-way Branching

29 29 Writing Nested if Statements Display one word to describe the int value of number as “Positive”, “Negative”, or “Zero” Your city classifies a pollution index less than 35 as “Pleasant”, 35 through 60 as “Unpleasant”, and above 60 as “Health Hazard.” Display the correct description of the pollution index value.

30 30 One Answer if (number > 0){ println( “Positive”); } else if (number < 0) { println( “Negative”); } else { println( “Zero”); }

31 31 Other Answer if ( index < 35 ) { println( “Pleasant”); } else if ( index <= 60 ) { println( “Unpleasant”); } else { println( “Health Hazard”); }

32 32 OperatorMeaning Associativity ! NOTRight *, /, % Multiplication, Division, Modulus Left +, - Addition, SubtractionLeft < Less thanLeft <= Less than or equal toLeft > Greater thanLeft >= Greater than or equal toLeft === Is equal toLeft !== Is not equal to Left && ANDLeft || OR Left = AssignmentRight

33 33 LOGICAL EXPRESSION MEANINGDESCRIPTION ! p NOT p ! p is false if p is true ! p is true if p is false p && q p AND q p && q is true if both p and q are true. It is false otherwise. p || q p OR qp || q is true if either p or q or both are true. It is false otherwise.

34 34 var age ; var isSenior, hasFever ; var temperature ; age = 20; temperature = 102.0 ; isSenior = (age >= 55) ; // isSenior is false hasFever = (temperature > 98.6) ; // hasFever is true EXPRESSIONVALUE isSenior && hasFever false isSenior || hasFever true ! isSeniortrue ! hasFeverfalse

35 35 What is the value? var age, height; age = 25; height = 70; EXPRESSIONVALUE ! (age < 10) ? ! (height > 60) ?

36 36 Write an expression for each taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22

37 37 Some Answers (taxRate >.25) && (income < 20000) (temperature <= 75) || (humidity <.70) (age > 21) && (age < 60) (age == 21) || (age == 22)

38 38 Use Precedence Chart var number ; var x ; number ! == 0 && x < 1 / number / has highest priority < next priority !== next priority && next priority

39 39 What went wrong? This is only supposed to display “HEALTHY AIR” if the air quality index is between 50 and 80. But when you tested it, it displayed “HEALTHY AIR” when the index was 35. int AQIndex ; AQIndex = 35 ; if (50 < AQIndex < 80) { println( “HEALTHY AIR“ ; }

40 40 Analysis of Situation AQIndex = 35; According to the precedence chart, the expression (50 < AQIndex < 80) means (50 < AQIndex) < 80 because < is Left Associative (50 < AQIndex) is false (has value 0) (0 < 80) is true.

41 41 Corrected Version var AQIndex ; AQIndex = 35 ; if ( (50 < AQIndex) && (AQIndex < 80) ) { println( “HEALTHY AIR“) ; }

42 42 Mouse Functions l mouseIsPressed n boolean function (use in if) l mouseButton (LEFT/RIGHT/CENTER) if (mouseIsPressed) { if (mouseButton === LEFT) { stroke(255); } else { stroke(0); }

43 43 Key Functions l keyIsPressed l key n char inputted l keyCode n ASCII code of char inputted n UP/DOWN n LEFT/RIGHT if (keyIsPressed) { if (keyCode === UP) { fill(255, 0, 0); } else { fill(255, 255, 255); } //============================== fill(255, 0, 0); textSize(450); var draw = function() { background(255); if (keyIsPressed) { text(key, 75, 325); } };


Download ppt "1 Conditions, Logical Expressions, and Selection Control Structures."

Similar presentations


Ads by Google