conditions, logical expressions, and selection control structures sumber dari :...

55
Conditions, Logical Expressions, and Selection Control Structures Sumber dari : www.cse.sc.edu/~rose/206/ppt/Chapter3.ppt

Upload: buddy-thornton

Post on 28-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Conditions, Logical Expressions,

and Selection Control Structures

Sumber dari : www.cse.sc.edu/~rose/206/ppt/Chapter3.ppt

Page 2: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Topics• Using Relational and Logical Operators to

Construct and Evaluate Logical Expressions• If-Then-Else Statements• If-Then Statements• Nested If Statements for Multi-way Branching

Page 3: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Flow of Control

• the order in which program statements are executed

WHAT ARE THE POSSIBILITIES. . .

Page 4: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Flow of Control

• is Sequential unless a “control structure” is used to change that

• there are 2 general types of control structures:

Selection (also called branching)

Repetition (also called looping)

Page 5: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

C++ control structures

• Selectionifif . . . else

• Repetitionfor loopwhile loopdo . . . while loop

Page 6: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Control Structuresuse logical expressions which may include:

6 Relational Operators< <= > >=

=== !==

3 Logical Operators! && ||

Page 7: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

=== 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 OperatorsThe == 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 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' // false0 == '' // true0 == '0' // true false == 'false' // falsefalse == '0' // true false == undefined // falsefalse == null // falsenull == undefined // true ' \t\r\n ' == 0 // trueThe 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.

Page 8: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

6 Relational Operators

are used in expressions of form:

ExpressionA Operator ExpressionB

temperature > humidity

B * B - 4.0 * A * C > 0.0

abs (number ) == 35

initial !== ‘Q’

Page 9: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

var x, y ;x = 4;y = 6;

EXPRESSION VALUE

x < y true

x + 2 < y false

x !== y true

x + 3 >= y true

y === x false

y === x+2 true

Page 10: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

IF / ELSE Statement

Page 11: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

If-Then-Else Syntax

if ( Expression ) {StatementA

}else {

StatementB }

NOTE: StatementA and StatementB each can be a single statement, a null statement, or a block.

Page 12: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

if ... else provides two-way selection

between executing one of 2 clauses (the if clause or the else clause)

TRUE FALSE

if clause else clause

expression

Page 13: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

If-Then-Else Example

if ( i < 0 ) {println( i + “ is negative”);

}else {

println( i + “ is non-negative”);}

Page 14: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Use of blocks required

if ( Expression ) {

}else{

}

“if clause”

“else clause”

Page 15: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

var carDoors, driverAge ; var premium, monthlyPayment ; . . .

if ( (carDoors === 4 ) && (driverAge > 24) ) { premium = 650.00 ; println( “ LOW RISK “ );

}

else {

premium = 1200.00 ; println( “ HIGH RISK ”) ;

}

monthlyPayment = premium / 12.0 + 5.00 ;

Page 16: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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

Page 17: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Solution

if ( purchase > 100.00 ) { discountRate = 0.25 ;

shipCost = 10.00 ;}else {

discountRate = .15 ; shipCost = 5.00 ;

}

totalBill = purchase * (1.0 - discountRate) + shipCost ;

Page 18: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

IF / THEN Statement

Page 19: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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

FALSEstatement

expression

Page 20: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

If-Then Syntax

if ( Expression ) {

Statement}

Page 21: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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.

Page 22: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Some Answers

if (taxCode === ‘T’) {price = price + taxRate * price;

}

if ( code === 1){

taxDue = income * taxRate;println( taxDue);

}

Page 23: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Remaining Answer

if ( ( A > 0 ) && (A < 5) ) {B = 1/A;

}else {

B = A;}

Page 24: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Both the if clause and the else clause

of an if...else statement can contain any kind of statement, including another selection statement.

Page 25: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Nested IF Statements

Page 26: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Multi-alternative Selection

is also called multi-way branching, andcan be accomplished by using NESTED if statements.

Page 27: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Nested if Statements

if ( Expression1 ) { Statement1

}else if ( Expression2 ) {

Statement2}

.

.else if ( ExpressionN ) {

StatementN}else { Statement N+1

}

EXACTLY 1 of these statements will be executed.

Page 28: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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.

Page 29: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Multi-way Branching

if ( creditsEarned >= 90 ) {

println(“SENIOR STATUS “); }else if ( creditsEarned >= 60 ) {

println(“JUNIOR STATUS “);

}else if ( creditsEarned >= 30 ) {

println(“SOPHOMORE STATUS “);

}else {

println(“FRESHMAN STATUS “); }

Page 30: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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 thepollution index value.

Page 31: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

One Answer

if (number > 0){

println( “Positive”);

}

else if (number < 0) {

println( “Negative”);

}

else {

println( “Zero”);

}

Page 32: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Other Answer

if ( index < 35 ) {

println( “Pleasant”);

}

else if ( index <= 60 ) {println( “Unpleasant”);

}

else {

println( “Health Hazard”);

}

Page 33: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Boolean Data values

• Boolean variables have 1 of just 2 values, the constants true and false

• we can declare variables of type bool

var hasFever; // true if has high temperature

var isSenior; // true if age is at least 55

isSenior = true;hasFever = false;

Page 34: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Boolean Values

var hasFever; // true if has high temperature

var isSenior; // true if age is at least 55

isSenior = true;hasFever = false;

if (isSenior) {println( “Apply for graduation.”;}

if (isSenior && !hasFever) {println( “Must attend graduation practice”;}

Page 35: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

In C++/JavaScript• the value 0 represents false

• ANY non-zero value represents true

Page 36: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

These are equivalent. Why?if (number === 0 ) if ( ! number ){ . { .

. . . . . .

} }

Each expression is only true when number has value 0.

Page 37: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Comparing Strings

• two objects of type string (or a string object and a C string) can be compared using the relational operators

• a character-by-character comparison is made using the ASCII character set values

• if all the characters are equal, then the 2 strings are equal. Otherwise, the string with the character with smaller ASCII value is the “lesser” string

Page 38: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

var myState; var yourState;

myState = “Texas”;yourState = “Maryland”;

EXPRESSION VALUE

myState === yourState false

myState > yourState true

myState === “Texas”true

myState < “texas”true

Page 39: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

39

LeftDigit(s)

3 ” ! “ # $ % & ‘

4 ( ) * + , - . / 0 1

5 2 3 4 5 6 7 8 9 : ;

6 < = > ? @ A B C D E

7 F G H I J K L M N O

8 P Q R S T U V W X Y

9 Z [ \ ] ^ _ ` a b c

10 d e f g h I j k l m

11 n o p q r s t u v w

12 x y z { | } ~

Right Digit ASCII (Printable) Character Set

0 1 2 3 4 5 6 7 8 9

Page 40: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Operator Meaning Associativity

! NOT Right

*, / , % Multiplication, Division, Modulus Left

+ , - Addition, Subtraction Left

< Less than Left

<= Less than or equal toLeft

> Greater than Left

>= Greater than or equal to Left

=== Is equal to Left

!= = Is not equal to Left

&& ANDLeft

|| OR Left

= AssignmentRight

Page 41: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

LOGICAL EXPRESSION MEANING DESCRIPTION

! 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 ifboth p and q are true. It is false otherwise.

p || q p OR q p || q is true if eitherp or q or both are true. It is false otherwise.

Page 42: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

var age ; var isSenior, hasFever ;var temperature ;

age = 20;temperature = 102.0 ;isSenior = (age >= 55) ; // isSenior is falsehasFever = (temperature > 98.6) ; // hasFever is true

EXPRESSION VALUE

isSenior && hasFever false

isSenior || hasFever true

! isSenior true

! hasFever false

Page 43: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

What is the value?

var age, height;

age = 25;height = 70;

EXPRESSION VALUE

!(age < 10) ?

!(height > 60) ?

Page 44: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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

Page 45: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Some Answers

(taxRate > .25) && (income < 20000)

(temperature <= 75) || (humidity < .70)

(age > 21) && (age < 60) (age == 21) || (age == 22)

Page 46: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Use Precedence Chart var number ;var x ;

number !== 0 && x < 1 / number

/ has highest priority< next priority!== next priority&& next priority

Page 47: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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“ ;

}

Page 48: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

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.

Page 49: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Corrected Version

var AQIndex ;AQIndex = 35 ;

if ( (50 < AQIndex) && (AQIndex < 80) ) {

println( “HEALTHY AIR“) ; }

Page 50: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Mouse Functions• mouseIsPressed

• boolean function (use in if)

• mouseButton (LEFT/RIGHT/CENTER) if (mouseIsPressed) { if (mouseButton === LEFT) { stroke(255); } else { stroke(0); } }

Page 51: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Key Functions• keyIsPressed

• key• char inputted

• keyCode• ASCII code of char inputted• UP/DOWN• 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); }};

Page 52: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Testing Selection Control Structures

• to test a program with branches, use enough data sets so that every branch is executed at least once

• this is called minimum complete coverage

Page 53: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

Testing Often Combines Two Approaches

WHITE BOX BLACK BOX TESTING TESTING

Code Coverage

Allows us to see the program code while designing the tests, so that data values at the boundaries, and possibly middle values, can be tested.

Data Coverage

Tries to test as many allowable data values as possible without regard to program code.

Page 54: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

How to Test a Program

• design and implement a test plan

• a test plan is a document that specifies the test cases to try, the reason for each, and the expected output

• implement the test plan by verifying that the program outputs the predicted results

Page 55: Conditions, Logical Expressions, and Selection Control Structures Sumber dari : rose/206/ppt/Chapter3.ppt

PHASE RESULT TESTING TECHNIQUE

Implementation Coded program Code walk-through, Trace

Compilation Object program Compiler messages

Execution Output Implement test plan

Problem solving Algorithm Algorithm walk-through