itm 352 flow-control: if and switch. itm 352 - © port, kazmanflow-control - 2 what is "flow of...

21
ITM 352 Flow-Control: if and switch

Upload: grace-fields

Post on 03-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

ITM 352

Flow-Control: if and switch

ITM 352 - © Port, Kazman Flow-Control - 2

What is "Flow of Control"?• Flow of Control is the execution order of instructions in a

program• All programs can be written with three control flow

elements:1. Sequence - just go to the next instruction2. Selection - a choice of at least two

either go to the next instructionor jump to some other instruction

3. Repetition - a loop (repeat a block of code) at the end of the loop

either go back and repeat the block of codeor continue with the next instruction after the block

• Selection and Repetition are called Branching since these are branch points in the flow of control

ITM 352 - © Port, Kazman Flow-Control - 3

The Type boolean• A primitive type• Can have expressions, values, constants, and variables just

as with any other primitive type• Only two values: true and false• Every expression is boolean in some way

• 0, 0.0, '0', '' are all false• Anything other than the above is true

• Comparison operators always return boolean

$is_desired_grade = ($grade == 'A');

$is_drinking_age = ($age >= 21);

$not_graduating = ($year != 'senior');

ITM 352 - © Port, Kazman Flow-Control - 4

Boolean Expressions• Boolean expressions can be thought of as test conditions (questions)

that are either true or false• Often two values (numbers, strings) are compared, return value is a

boolean (i.e. true or false)• For example:

Is A greater than B?, Is A equal to B?, Is A less than or equal to B?• Comparison operators are used for boolean expressions

(<, >, <=, >=, ==, ===, !=. !==, …)• A and B can be any data type (or class), but they generally are a

"compatible" data type (or class)• Comparisons are either numeric or lexicographic but can be user-defined

via objects and functions.• Comparing non-compatible types is legal but may have unexpected

results.

ITM 352 - © Port, Kazman Flow-Control - 5

Basic PHP Comparison Operators

Math Notation

Name

PHP Notation

PHP Examples

= equal to == $balance == 0 $answer == 'y'

not equal to != $income != tax $answer != 'y'

> greater than

> $income > $outgo

greater than or equal to

>= $points >= 60

< less than

< $pressure < $max

less than or equal to <= $income <= $outgo

ITM 352 - © Port, Kazman Flow-Control - 6

A Note on Printing Boolean Values

• The echo (and print) command will convert values to strings for printing• true is converted to '1'• false is converted to “” (the empty string)

• echo true

1• echo false

<no output>

ITM 352 - © Port, Kazman Flow-Control - 7

"Identical" Comparison Operators

• Sometimes you really want to be sure two values are exactly the same value and type• Is 0.0 equal to 0?

• Use the '===' and '!==' to test equality and non-equality for both value and type• 0.0 == 0 returns true• 0.0 === 0 returns false

Do lab exercise #1

ITM 352 - © Port, Kazman Flow-Control - 8

Compound Boolean Expressions• Use && or and to AND (intersect) two or more conditions• Use || to OR (union) two or more conditions• See text for definitions of AND and OR• For example, write a test to see if B is either 0 or between the

values of A and C :(B == 0) || (A <= B && B < C)(B == 0) or (A <= B) and B < C)

• In this example the parentheses are not required but are added for clarity

• Subject to Precedence rules• Note the short-circuit, or lazy, evaluation rules (later in slides)• Use a single & for AND and a single | for OR to avoid short-

circuit evaluation and force complete evaluation of an expression

ITM 352 - © Port, Kazman Flow-Control - 9

Truth Tables for boolean Operators

Value of A Value of B A && B

true true true

true false false

false true false

false false false

Value of A Value of B A || B

true true true

true false true

false true true

false false false

Value of A !A

true false

false true

&& (and) || (or)

! (not)

ITM 352 - © Port, Kazman Flow-Control - 10

Precedence Rules for Common Operators

Highest Precedence• the unary operators: ++, --, and !• the binary arithmetic operators: *, /, %• the binary arithmetic operators: +, -• the boolean operators: <, >, =<, >=• the boolean operators: ==, !=• the boolean operator &• the boolean operator |• the boolean operator &&• the boolean operator ||

Lowest Precedence

Do lab exercise #2

ITM 352 - © Port, Kazman Flow-Control - 11

PHP Flow Control Statements

Sequential• the default• PHP automatically

executes the next instruction unless you use a branching statement

Branching: Selection• if• if-else• if-else if-else if- … - else

• switchBranching: Repetition• while• do-while• for• foreach

ITM 352 - © Port, Kazman Flow-Control - 12

PHP if statement

• Simple decisions• Do the next statement if test is true or skip it if false

• Syntax:if (Boolean_Expression)

Action if true; //execute if true

next action; //always executed

• Note the indentation for readability (not compiler or execution correctness)

ITM 352 - © Port, Kazman Flow-Control - 13

if Example

• The body of the if statement is conditionally executed

• Statements after the body of the if statement always execute (not conditional unless grouped inside {}'s)

if ($eggsPerBasket < 12) //begin body of the if statement echo "Less than a dozen eggs per basket"; //end body of the if statement$totalEggs = $numberOfEggs * $eggsPerBasket;echo "You have a total of $totalEggs eggs.";

ITM 352 - © Port, Kazman Flow-Control - 14

PHP Statement Blocks:Compound Statements

• Action if(true) can be either a single statement or a set of statements enclosed in curly brackets (a compound statement, or block). For example:

if ($eggsPerBasket < 12){ //begin body of the if statement echo "Less than a dozen ..."; $costPerBasket = 1.1 * $costPerBasket;} //end body of the if statement

$totalEggs = $numberOfEggs * $eggsPerBasket;echo "You have a total of $totalEggs eggs.");

All statements between braces are controlled by if

ITM 352 - © Port, Kazman Flow-Control - 15

PHP Statement Blocks:Compound Statements

Alternatively, "if(<exp>): … endif; " also works:

if ($eggsPerBasket < 12) ://begin body of the if statement echo "Less than a dozen ..."; $costPerBasket = 1.1 * $costPerBasket;//end body of the if statementendif;

$totalEggs = $numberOfEggs * $eggsPerBasket;echo "You have a total of $totalEggs eggs.");

All statements between : and endif; are controlled by if

This style is useful when using PHP in large blocks of HTML (see example in textbook)

Do lab exercise #3

ITM 352 - © Port, Kazman Flow-Control - 16

Two-way Selection: if-else• Select either one of two options• Either do Action1 or Action2, depending on test value• Syntax:

if (Boolean_Expression)

{

Action1 //execute only if Boolean_Expression true

}

else

{

Action2 //execute only if Boolean_Expression false

}

Action3 //anything here always executed

ITM 352 - © Port, Kazman Flow-Control - 17

if-else Examples

• Example with single-statement blocks:if ($time < $limit) echo "You made it.";else

echo "You missed the deadline.";

• Example with compound statements:if ($time < $limit){ echo "You made it."; $bonus = 100;}else{ echo "You missed the deadline."; $bonus = 0;}

Do lab exercise #4

ITM 352 - © Port, Kazman Flow-Control - 18

Multibranch selection:if-else if-elseif-…-else

• One way to handle situations with more than two possibilities

• Syntax:if(Boolean_Expression_1) Action_1elseif(Boolean_Expression_2) Action_2 . . .elseif(Boolean_Expression_n) Action_nelse Default_Action

ITM 352 - © Port, Kazman Flow-Control - 19

if-elseif-elseif-…-else Example

if($score >= 90 && $score <= 100)

$grade= 'A';

elseif ($score >= 80)

$grade= 'B';

elseif ($score >= 70)

$grade= 'C';

elseif ($score >= 60)

$grade= 'D';

else

$grade= 'E';

• Note how the sequence is important here and must use elseif rather than just if (why?)

ITM 352 - © Port, Kazman Flow-Control - 20

if-elseif-elseif-…-else Non-Example??

if ($profRel == "colleague" ) $greeting = "Thomas";elseif ($profRel == "friend" ) $greeting = "Tom";elseif ($profRel == "grad student" ) $greeting = "TC";elseif ($profRel == "undergrad student" ) $greeting = "professor";else

$greeting = "Dr. Collins";

ITM 352 - © Port, Kazman Flow-Control - 21

Use switch for single-variable if

switch($profRel) {case "colleague" :

$greeting = "Thomas";break;

case "friend" : $greeting = "Tom";

break;case "grad student" :

$greeting = "TC";break;

case "undergrad student" : $greeting = "professor";

break;default :

$greeting = "Dr. Collins";break;

}Do lab exercise #5