# Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS

## Presentation on theme: "Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS"— Presentation transcript:

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 balance = balance + (INTEREST_RATE * balance) / 12; else balance = balance - OVERDRAWN_PENALTY; do you have money? Execute balance = balance + (INTEREST_RATE * balance) / 12; Execute balance = balance - OVERDRAWN_PENALTY; True False Condition or Boolean expression Actions

Boolean Expressions Compare two operands

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

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

Logical Operators Same operators as in binary numbers (Sub_Expression_1) operator (Sub_Expression_2) Logical operatorJava operator AND&& OR|| NOT!

Using AND and OR 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"); Are parentheses necessary?

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

Avoiding Negation

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

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 min) || (!(pressure < max))  (pressure = max)

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;

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;

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;

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");

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

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); }

Comparing Strings Use the equals() method Use equalsIgnoreCase() for case insensitive comparison How about using == with strings? How about now? if (“hello”.equals(“hello”)) System.out.println(“All is well”); String objects 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?”);

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);

The Boolean Type Using Boolean variables can make your programs easier to read boolean systemsAreOK = ((temperature = 12000) && (cabinPressure > 30) if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launch sequence."); if ((temperature = 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)

Short-Circuit Evaluation (expressionA) || (expressionB)(expressionA) && (expressionB) expressionAexpressionB&& false truefalse truefalse true expressionAexpressionB|| false truefalsetrue falsetrue Can we optimize the common case?

Revisiting Operator Precedence OperatorsPrecedence postfixexpr++ expr-- unary++expr --expr +expr -expr ~ ! multiplicative* / % additive+ - shift > >>> relational = instanceof equality== != bitwise AND& bitwise exclusive OR^ bitwise inclusive OR| logical AND&& logical OR|| ternary? : assignment= += -= *= /= %= &= ^= |= >= >>>=

The switch Statement 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."); Before using multibranch if-else statements 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; } After … using switch

Switch Syntax The Controlling_Expression must 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 SYNTAX switch (Controlling_Expression) { case Case_Label: Statement;... Statement; break; case Case_Label: Statement;... Statement; break; default: Statement;... Statement; break; }

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: 1.letter = ‘a’; 2.letter = ‘B’; 3.letter = ‘c’;

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: int movieStars; // 0  bad, 1  average, 2  excellent Approach 2: enum MovieRating { EXCELLENT, AVERAGE, BAD }; MovieRating movieStars = MovieRating.AVERAGE;

Using Enumerations with the Switch statement 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."); } Case labels are assumed to belong to the enumeration in the switch expression

Download ppt "Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS"

Similar presentations