1 of 12

Control Structures II

October 7, 2015

2 of 12

Control Structures II

  • Review
  • Nested IF/ELSE
  • And/Or Operator
  • Short Circuit Evaluation
  • Switch
  • Not Operator

3 of 12

HW REVIEW

4 of 12

Review

  • What can a boolean variable hold?
  • What are these: !=, ==, >, <, >=, <=
  • What happens in this program when points = 2? points =1? points = 7

5 of 12

Nested If Statements

  • We can put if statements inside of if, else or else if statements
  • You can do this within if, else, or else if blocks
  • Really helps when dealing with complicated logic and ranges

6 of 12

And Operator

  • Used in boolean statements to create a compound expression
  • It only allows the boolean statement to be true if BOTH statements are true
  • Denoted by two ampersand signs (&&) between two boolean expressions
    • boolean seahawksWin = ((russelWilsonYards > 0) && (camChancellorPlays == “yes”));

7 of 12

Or Operator

  • Can be used in a compound boolean expression
  • It is used when you want to create a boolean expression that is true when at least one of the boolean clauses is true
  • Denoted by two vertical bars (||)
    • boolean shouldIPlayWithAnimal = ((animal == “cat”) || (animal == “dog”));

8 of 12

Short Circuit Evaluation

  • Short circuit evaluation occurs when no more computation is needed to determine the answer
  • Both && and || use short circuit evaluation
    • && : if the first clause is false, we know the whole expression will be false
    • || : if the first clause is true, then we know the whole expression must be true
  • String animal = “cat”;
  • boolean shouldIPlayWithAnimal = ((animal == “cat”) || (animal == “dog”));

  • int russellWilsonYards = 0;
  • boolean seahawksWin = ((russelWilsonYards > 0) && (camChancellorPlays == “yes”));

9 of 12

Switch Statement

  • We could write a bunch of if statements when testing one variable but there is a cleaner way of doing it
  • Switch Statement
    • in the parenthesis is the expression you would like to evaluate: “grade”
    • each case is a possible value
    • break tells the switch statement to terminate
    • default is optional and runs when the grade is not found (similar to else)

10 of 12

Not operator

  • Negates any boolean expression
  • If the boolean expression was true, with the not operator it becomes false
  • if the the boolean expression was false, it now becomes true
  • The not operator must precede the boolean expression it will negate

11 of 12

Operator precedence

  • The book talks about operator precedence on page 283
  • I like to view it a simpler way, if you’re not sure of which operator will have precedence, use parentheses and you can explicitly state which one should come first

12 of 12

LAB/HW

No class 10/11 & 10/12