1 / 31

Intro to CS – Honors I Control Flow: Branches

Intro to CS – Honors I Control Flow: Branches. Georgios Portokalidis gportoka@stevens.edu. Control Flow. Control flow is very important! Control flow allows a program to take decisions Choose an option from a list of options. If-Else. if you_have_money_in_the_bank then

tacey
Télécharger la présentation

Intro to CS – Honors I Control Flow: Branches

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to CS – Honors IControl Flow: Branches Georgios Portokalidis gportoka@stevens.edu

  2. Control Flow • Control flow is very important! • Control flow allows a program to take decisions • Choose an option from a list of options

  3. If-Else if you_have_money_in_the_bank then balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; Condition or Boolean expression do you have money? Actions False True Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY;

  4. Boolean Expressions • Compare two operands

  5. If-Else Revisited if (balance >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; if (Boolean_Expression) Statement_1 else Statement_2 balance >= 0 False True Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY;

  6. Common Errors • Using = instead of == • Example: if (balance = 2) • What is the effect of the above? • Comparing floating-point values with == or != • Remember that floating-point numbers are an approximation • Better to check if a number is within a range! • Example: min < pressure < max This is not a valid expression

  7. Logical Operators • Same operators as in binary numbers • (Sub_Expression_1) operator (Sub_Expression_2)

  8. Using AND and OR Are parentheses necessary? if ((pressure > min) && (pressure < max)) System.out.println("Pressure is OK."); else System.out.println("Warning: Pressure is out of range."); if ((salary > expenses) ||(savings > expenses)) System.out.println("Solvent"); else System.out.println("Bankrupt");

  9. The Negation Operator • if (!(number >= min)) System.out.println("Too small"); • else System.out.println("OK")

  10. Avoiding Negation

  11. If-without-else • if (balance >= 0) • balance = balance + (INTEREST_RATE * balance) / 12; System.out.println(“New balance: “ + balance); do you have money? False True Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute next statement

  12. Avoiding Negation II • Consider the following: • if (!((pressure > min) && (pressure < max))) System.out.println(“Houston we have a problem!"); • Is there an equivalent without negation? • !((pressure > min) && (pressure < max))  (!(pressure > min) || (!(pressure < max))  • (pressure <= min) || (pressure >= max)

  13. Nested if-else Statements • if (balance >= 0) • Apply interest rate expression • else • balance = balance − OVERDRAWN_PENALTY; if (balance >= 0) if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else System.out.println("Cannot have a negative interest."); else balance = balance − OVERDRAWN_PENALTY;

  14. Use Braces for Clarity if (balance >= 0) { if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance) / 12; else System.out.println("Cannot have a negative interest."); } else balance = balance − OVERDRAWN_PENALTY;

  15. Use Braces for Correction • else always matches the last unmatched if //First Version − Braces if (balance >= 0) { if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance)/12; } else balance = balance − OVERDRAWN_PENALTY; //Second Version - No Braces if (balance >= 0) if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance)/12; else balance = balance − OVERDRAWN_PENALTY;

  16. Multibranch if-else Statements if (balance > 0) System.out.println("Positive balance"); else if (balance < 0) System.out.println("Negative balance"); else if (balance == 0) System.out.println("Zero balance"); if (balance > 0) System.out.println("Positive balance"); else if (balance < 0) System.out.println("Negative balance"); else if (balance == 0) System.out.println("Zero balance");

  17. The Conditional Operator if (n1 > n2) max = n1; else max = n2; max = (n1 > n2) ? n1 : n2;

  18. Using exit to End a Program if (numberOfWinners == 0) { System.out.println("Error: Dividing by zero."); System.exit(0); } else { oneShare= payoff / numberOfWinners; System.out.println("Each winner will receive $" + oneShare); }

  19. Comparing Strings Use the equals() method Use equalsIgnoreCase() for case insensitive comparison How about using == with strings? How about now? String objects if (“hello”.equals(“hello”)) System.out.println(“All is well”); if (“hello”.equalsIgnoreCase(“Hello”)) System.out.println(“All is well”); if (“hello” == “hello”) System.out.println(“Should this work?”); String s1 = new String(“hello”); String s2 = new String(“hello”); if (s1 == s2) System.out.println(“Should this work?”);

  20. Lexicographic Comparison • s1.compareTo(s2) • Returns • A negative number if s1 comes before s2 • Zero if the strings are equal • A positive number if s1 comes after s2 if (s1.compareTo(s2) < 0) System.out.println(s1 + " precedes " + s2 + " in lexicographic ordering"); else if (s1.compareTo(s2) > 0) System.out.println(s1 + " follows " + s2 + " in lexicographic ordering"); else //s1.compareTo(s2) == 0 System.out.println(s1 + " equals " + s2);

  21. The Boolean Type • Using Boolean variables can make your programs easier to read if ((temperature <= 100) && (thrust >= 12000) && (cabinPressure > 30)) System.out.println("Initiate launch sequence."); else System.out.println("Abort launch sequence."); Boolean variables can be assigned (booleanVariable) can be used instead of (booleanVariable == true) booleansystemsAreOK = ((temperature <= 100) && (thrust >= 12000) && (cabinPressure > 30) if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launch sequence.");

  22. Short-Circuit Evaluation (expressionA) || (expressionB) (expressionA) && (expressionB) Can we optimize the common case?

  23. Revisiting Operator Precedence

  24. After … using switch The switch Statement • switch (numberOfBabies) • { • case 1: • System.out.println("Congratulations."); • break; • case 2: • System.out.println("Wow. Twins."); • break; • case 3: • System.out.println("Wow. Triplets."); • break; • case 4: • case 5: • System.out.print("Unbelievable; "); • System.out.println(numberOfBabies+ • " babies."); • break; • default: • System.out.println("I don't believe you."); • break; • } Before using multibranch if-else statements if (numberOfBabies == 1) System.out.println("Congratulations."); else if (numberOfBabies == 2) System.out.println("Wow. Twins."); else if (numberOfBabies == 3) System.out.println("Wow. Triplets."); else if (numberOfBabies == 4 || numberOfBabies == 5) { System.out.print("Unbelievable; "); System.out.println(numberOfBabies+ " babies."); } else System.out.println("I don't believe you.");

  25. Switch Syntax • SYNTAX • switch (Controlling_Expression) • { • case Case_Label: • Statement; • ... • Statement; • break; • case Case_Label: • Statement; • ... • Statement; • break; • default: • Statement; • ... • Statement; • break; • } • The Controlling_Expressionmust be of an integer type • int, short, byte or char • Each Case_Label is a constant of the same type as the Controlling_Expression • Each case must have a different Case_Label • A break may be omitted • Without a break, execution just continues to the next case • Any number of cases is allowed • A default case is optional • Without one, no action occurs in the event of a mismatch

  26. Omitting break • switch (letter) • { • case'A': • case'a': • System.out.println("Some kind of A."); • case'B': • case'b': • System.out.println("Some kind of B."); • break; • default: • System.out.println("Something else."); • break; • } What happens in this example, when: letter = ‘a’; letter = ‘B’; letter = ‘c’;

  27. Enumerations • An enumeration provides a way to restrict the value of a variable • For example: you want to create an application for rating movies as excellent, average, or bad • Approach 1: • intmovieStars; // 0  bad, 1 average, 2excellent • Approach 2: • enumMovieRating { EXCELLENT, AVERAGE, BAD }; • MovieRatingmovieStars = MovieRating.AVERAGE;

  28. Using Enumerations with the Switch statement Case labels are assumed to belong to the enumeration in the switch expression • switch (rating) • { • case E: //Excellent • System.out.println("You must see this movie!"); • break; • case A: //Average • System.out.println("This movie is OK, but not great."); • break; • case B: //Bad • System.out.println("Skip it!"); • break; • default: • System.out.println("Something is wrong."); • }

More Related