490 likes | 661 Views
Control Structures. special statements whose purpose is to change the order of execution in a program. Sequential structures – Statements executed sequentially Selection structures Repetition structures (loop). Selection. Given hours worked and pay rate, calculate total pay
E N D
Control Structures • special statements whose purpose is to change the order of execution in a program. • Sequential structures – Statements executed sequentially • Selection structures • Repetition structures (loop) decision.ppt
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
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
What is truth? • 0 is false • anything other than 0 is true decision.ppt
Relational Operators decision.ppt
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 + 2true ‘r’ < ‘t’ true decision.ppt
Beware:== vs = • = assignment • == test for equality • x = 5; • if (x == 5) decision.ppt
Java Operator Precedence decision.ppt
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
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
equals – tests objects for equality • str1.equals(str2) • str1.equalsIgnoreCase(str2); • if (s.equalsIgnoreCase("yes")) decision.ppt
Logical Operators decision.ppt
&& - Logical AND decision.ppt
|| - Logical OR decision.ppt
! Not decision.ppt
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) Note: left expression is equivalent to right expression with! added and the relational and logical operators reversed decision.ppt
Java Operator Precedence decision.ppt
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
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
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
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
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
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
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("Finalgrade 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
if Syntax if ( Expression ) Statement NOTE: Statement can be a single statement, a null statement, or a block (compound statement). decision.ppt
if statement is a selection of whether or not to execute a statement (which can be a single statement or an entire block) TRUE expression FALSE statement decision.ppt
if • Single statement EX1: if (number % 2 == 0) System.out.println("Even number!"); EX2: if (i) { //defensive programming System.out.println(iis nonzero"; } decision.ppt
compound statement • Multiple statements where one is allowed if (state == MD) { amt = amt + (amt * .05); cout<<amt; } decision.ppt
if elsesyntax if (Expression ) StatementA else StatementB NOTE: StatementA and StatementB each can be a single statement, a null statement, or a compound statement. decision.ppt
if..else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE expression if clause else clause decision.ppt
if (i >= 0) { System.out.println("positive"); } else { System.out.println("negative"); } 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. Example: decision.ppt
=> Watch out for null statement if (x > 0); //does nothing if (x >0); //hard to find bug System.out.println("Positive"); decision.ppt
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
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
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
version 1:separate ifs if (x > 0) posCount++; if (x < 0) negCount++; if (x==0) zeroCount++; How many branches are tested, best case, worst case? 3 way choice decision.ppt
Version 2: Nested ifs if (x > 0) posCount++; else if (x < 0) negCount++; else zeroCount++; How many branches are tested, best case, worst case? 3 way choice decision.ppt
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? 3 way choice decision.ppt
if (cond) statement else if (cond) statement else if (cond) statement else 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 else if decision.ppt
if (temp <= 32) System.out.println("freezing"); if (temp >= 212) System.out.println("boiling"); if ((temp >= 32) and (temp <= 212)) System.out.println("liquid“); if (temp <= 32) System.out.println("freezing"); else if (temp >= 212) System.out.println("boiling"); else System.out.println("liquid“); Example: decision.ppt
if (n > 0) if (a > b) z = a; else z = b; if (n > 0) if (a > b) z = a; else z = b; Dangling else:else matches with most recent unmatched if autoformatting in IDEs is a good way to catch many of these kinds of errors decision.ppt
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; } Overtime example decision.ppt
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; } Overtime example decision.ppt
Grade Example 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." ) decision.ppt
?: • expression1 ? expression2:expression3 max = (a>=b) ? a : b; if (a >= b) max = a; else max = b; decision.ppt
switch switch (expression) { case value1: statements break; case value2: statements break; … default: statements } decision.ppt
import java.util.*; public class Switch { public static void main (String [] args) { Scanner a = new Scanner(System.in); intyearLevel; System.out.print("Enter year Level: "); yearLevel = a.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