Decision.ppt1 Control Structures special statements whose purpose is to change the order of...

Post on 11-Jan-2016

214 views 0 download

Transcript of Decision.ppt1 Control Structures special statements whose purpose is to change the order of...

decision.ppt 1

Control Structures

• special statements whose purpose is to change the order of execution in a program.

1. Sequential structures – Statements executed sequentially

2. Selection structures

3. Repetition structures (loop)

decision.ppt 2

Selection

• Given hours worked and pay rate, calculate total pay

• How about if you work overtime?• How do you indicate if your work

overtime?• How about double overtime?

decision.ppt 3

Selection

• Single-selection structure – The if structure – selects or ignores a single action.

• Double-selection structure – The if/else structure – selects between two different actions.

• Multiple-selection structure – The switch structure – selects one of many possible actions (to be

discussed later)

decision.ppt 4

What is truth?

• 0 is false• anything other than 0 is true

decision.ppt 5

Relational Operators

< Less than<= less than or equal to

> greater than

>= Greater than or equal to

== equals

!= not equal to

decision.ppt 6

examples: int  x = 4; int  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

'r' < 't' true

decision.ppt 7

Beware:== vs =

• = assignment• == test for equality• x = 5;• if (x == 5)• if (x=5)

– Has two unexpected results– Assigns x a 5– Evaluates to true

• Hard to find bug

decision.ppt 8

Java Operator Precedence

Description operatorUnary ++, --, +, -

Multiplicative *, /, %

Additive +, -

Relational <, >, <=, >=

Equality ==, !=

Assignment =, +=, -=, *=, /=, %=

decision.ppt 9

Comparing strings

• str1.compareTo(str2)– Compares two string lexicographically– A negative integer value if str1 < str2– 0 if str1 is equivalent to str2– A positive integer if str1 > str2

decision.ppt 10

Example

>String str1 = "Hello";>String str2 = "Hi";>System.out.println(str1.compareTo(str2));-4> System.out.println(str2.compareTo("Hi"));0> System.out.println(str2.compareTo("Big"));

6

decision.ppt 11

equals – tests objects for equality

• str1.equals(str2)• str1.equalsIgnoreCase(str2);• if (s.equalsIgnoreCase("yes"))

decision.ppt 12

Logical Operators

Operator Meaning Syntax

&& AND exp1 && exp2

|| OR exp1 || exp2

! NOT !exp1

decision.ppt 13

P    Q  P && Q

true true true

true false false

false true false

false false false

&& - Logical AND

decision.ppt 14

P Q P || Q

true true true

true false true

false true true

false false false

|| - Logical OR

decision.ppt 15

P !P

true false

false true

! Not

decision.ppt 16

DeMorgan's Law:    not(P and Q) is equivalent to (not P) or (not Q),  !(P && Q) = (!P) || (!Q)

     not(P or Q) is equivalent to (not P) and (not Q),  !(P || Q) = (!P) && (!Q)  

Expression Equivalent Expression

!(P == Q) P != Q

!(P == Q | | P == R) P != Q && P != R

!(P == Q && P == R) P != Q | | P != R

!(P == Q && R > S) P !=Q | | R <=S

Note: left expression is equivalent to right expression with! added and the relational and logical operators reversed

decision.ppt 17

Java Operator PrecedenceDescription operator

Unary ++, --, +, -, !

Multiplicative *, /, %

Additive +, -

Relational <, >, <=, >=

Equality ==, !=

Assignment =, +=, -=, *=, /=, %=

Logical And &&

Logical Or ||

Assignment =

decision.ppt 18

Examples:• Do not depend on operator precedence while

using expressions containing side-effects – x>3 && x++

• 5 > 2 && 4 > 7 false• 5 > 2 || 4 < 7 true• !(4 < 7) false• if ((sex == 'F') && (cityCode == 18) && (gpa >= 3.8))• if ((zipCode.equals("48002")) || (zipCode.equals("48003")) || (zipCode.equals( "48004"))• !(hours > 40)  same as: hours <=  40     

decision.ppt 19

Short-Circuit Evaluation

• evaluation proceeds from left to right• the computer stops evaluating sub-expressions

as soon as the truth value of the entire expression can be determined

• Exercise caution when the operands following the first operand contain side effects (see notes)

• Rule of thumb: • first true in OR => Entire expression is true • first false in AND => Entire expression is false

decision.ppt 20

Short-Circuit Examples: • int age = 25; int weight = 150;

• (age > 50) && (weight > 140)  // false – Evaluation can stop after determining that (age >

50) is false, it is already determined that the entire expression will be false.

• (weight >= 150)||(age > 40)  // true– Evaluation can stop after determining that

(weight >= 50) is true, it is already determined that the entire expression will be true.

• (age < 50) && (weight > 140)  // true – After determining that (age < 50) is true, we

have to determine the truth value of the second part.

• (age < 20) || (weight < 140)  // false – After determining that (age < 20) is false, we

have to determine the truth value of the second part.

decision.ppt 21

Exercises• Write an expression for the following:

– 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

• For what value(s) of x would this condition be true?– (x < 1) && (x > 10)

• For what value(s) of y would this condition be true?– (y >= 1) && (y <= 10)

decision.ppt 22

Example

• x > y + 2 => x > (y + 2)• x + 3 <= y * 10• a <= b > c < d >= e will be executed as:

( ) > c ( ) < d ( ) >= e ( )

decision.ppt 23

Relational Operators with Floating Point Types

• Do not compare floating-point numbers for equality; approximate values, they are rarely exactly equal.

• test for near equality • compute the difference between the 2 numbers and

check if the result is less than some max difference. – Example:

float x = 1.0; float y = 3.0; float z; ... z = x/y; ... if (x == z * y)... // x will not be 1.0, but 0.99999 if (abs(x - z * y) < 0.00001)... // close enough

decision.ppt 24

Compound Logical Expressions

• if (a < b < c)– syntax error– In this expression, c is compared with 1 or 0 (the

result of evaluating a < b• int  total = 50;

if (80 < total < 90)      System.out.println("Final grade is B");

• According to the precedence chart, the expression(80 < total < 90) means (80 < total) < 90  because "<" is left associative, (80 < total ) is false

(false < 90) is invalid.if ((80 < total) && (total < 90)) //correction

decision.ppt 25

if ( Expression )

Statement

NOTE: Statement can be a single statement, a null statement, or a block (compound statement).

if Syntax

decision.ppt 26

if 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

decision.ppt 27

if• Single statementEX1: if (number % 2 == 0) System.out.println("Even number!");

EX2: if (i){ //defensive programming

System.out.println(i is nonzero";}

decision.ppt 28

compound statement

• Multiple statements where one is allowed

if (state == MD)

{

amt = amt + (amt * .05);

cout <<amt;

}

decision.ppt 29

if (Expression )

StatementA

elseStatementB

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

if else syntax

decision.ppt 30

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

decision.ppt 31

if (i >= 0)

{

System.out.println("positive");

}

else

{

System.out.println("negative");

}

Example:if (i >= 0)

System.out.println("positive");

else

System.out.println("negative");

• braces may be omitted if there is only one clause:

• Recommended - leaving the braces in case another statement is added.

decision.ppt 32

=> Watch out for null statement

if (x > 0); //does nothing

if (x > 0); //hard to find bug System.out.println("Positive");

decision.ppt 33

Nested IF Statements

• The body of an if-clause or else-clause can contain another if or if-else statement

• this is called a nested control structure or a nested if

• In general, any problem that involves a multiway branch (more than 2 alternative solutions) can use nested if statements.

decision.ppt 34

if (x > 0) System.out.println("Positive");else // nested if else

if (x < 0) System.out.println("Negative");

else System.out.println("Zero");

decision.ppt 35

change indentation (remove whitespace)

if (x > 0) System.out.println("Positive");else if (x < 0) System.out.println("Negative");

else System.out.println("Zero");

decision.ppt 36

3 way choice

• version 1:separate ifsif (x > 0) posCount++;if (x < 0) negCount++;if (x==0) zeroCount++;• How many branches are tested, best

case, worst case?

decision.ppt 37

3 way choice

• Version 2: Nested ifsif (x > 0) posCount++;else if (x < 0) negCount++; else zeroCount++;• How many branches are tested, best

case, worst case?

decision.ppt 38

3 way choice• Version 3: Nested ifs, special

indentation (preferred version)

if (x > 0) posCount++;else if (x < 0) negCount++;else zeroCount++; • How many branches are tested, best

case, worst case?

decision.ppt 39

else if

if (cond) statementelse if (cond) statementelse if (cond) statementelse statement

• evaluated in order, if any expression is true, that statement and that statement only is executed.

• only difference is whitespace

• preferred method - shows we are making a choice

decision.ppt 40

Example:

if (temp <= 32) System.out.println("freeze");

if (temp >= 212)System.out.println("boil");

if ((temp >= 32) and (temp <= 212))

System.out.println("liquid");

if (temp <= 32)System.out.println("freeze";

else if (temp >= 212) System.out.println("boil");

else

System.out.println("liquid");

decision.ppt 41

Situation Construct Basic formYou want to execute any combination of control statements

Sequentials ifs if (<test1>) <statement1>;if (<test2>) <statement2>;if (<testn>) <statementn>;

You want to execute zero or one of the control statements

Nested ifs ending in test if (<test1>) <statement1>;else if (<test2>) <statement2>;else if (<testn>) <statementn>;

You want to execute exactly one of the controlled statements

Nested ifs ending in else if (<test1>) <statement1>;else if (<test2>) <statement2>;else <statementn>;

decision.ppt 42

Dangling else:else matches with most recent unmatched if

if (n > 0) if (a > b)

z = a;else z = b;

if (n > 0) if (a > b)

z = a;else z = b;

autoformatting in IDEs is a good way to catch many of these kinds of errors

decision.ppt 43

Dangling elseif ( num > 0 ) if ( num < 10 ) System.out.println("aaa") ; else System.out.println("bbb") ;

if ( num > 0 ) if ( num < 10 ) System.out.println("aaa") ; else System.out.println("bbb") ;

decision.ppt 44

Overtime example

if (hours <= 40) totalPay = hours * payRate;else if (hours <= 60){ regPay = 40 * payRate; otPay = (hours – 40) * payRate * 1.5; totalPay = regPay + otPay;}else{ regPay = 40 * payRate; otPay = 20 * payRate * 1.5; doubleOtPay =(hours – 60)* 2 * payRate; totalPay = regPay + otPay + doubleOtPay;

}

decision.ppt 45

Overtime example

if ((hours < 0 || (hours > 168)) System.out.println("Invalid");else if (hours <= 40) totalPay = hours * payRate;else if (hours <= 60){ regPay = 40 * payRate; otPay = (hours – 40) * payRate * 1.5; totalPay = regPay + otPay;}else{ regPay = 40 * payRate; otPay = 20 * payRate * 1.5; doubleOtPay =(hours – 60)* 2 * payRate; totalPay = regPay + otPay + doubleOtPay;

}

decision.ppt 46

int grade;

// Get grade System.out.println( "Enter the grade:"); grade = console.nextInt(); System.out.println( "Your grade of " + grade + " is ");

// Print letter grade if (grade >= 90) System.out.println( "A." ); else if (grade > 80) System.out.println( "B." ); else if (grade >= 70) System.out.println( "C." ); else if (grade >= 60) System.out.println( "D." ); else

System.out.println( "F." )

Grade Example

decision.ppt 47

?:

• expression1 ? expression2:expression3

max = (a>=b) ? a : b;

if (a >= b)

max = a;

else

max = b;

decision.ppt 48

switchswitch (expression){case value1: statements break;case value2: statements break; …default: statements}

decision.ppt 49

switch• switch works with:

– byte, short, char, and int primitive data types.– enumerated types – the String class,– and a few special classes that wrap certain primitive

types: Character, Byte, Short, Int• All switch statements can be re-written as if..else• Not all if..else can be rewritten as switch

• An if-then-else statement can test expressions based on ranges of values or conditions,

• whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object

decision.ppt 50

break

Each break statement terminates the enclosing switch statement.Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

decision.ppt 51

import java.util.*;public class Switch { public static void main (String [] args) { Scanner console = new Scanner(System.in); int yearLevel; System.out.print("Enter year Level: "); yearLevel = console.nextInt(); switch (yearLevel) { case 1: System.out.println("You are a freshman!"); break; case 2: System.out.println("You are a sophomore!"); break; case 3: System.out.println("You are a junior!"); break; case 4: System.out.println("You are a Senior!"); break; default: System.out.println("Invalid entry!"); break; } }}

decision.ppt 52

import java.util.*;public class SwitchDemo { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter month: "); int month = console.nextInt(); switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } }