More Selection Executing Statements Selectively Chap. 7 (Read §7.1-7.4 & Part of Picture: Boolean Logic and Digital Design) 1.

Slides:



Advertisements
Similar presentations
The if-else Statements
Advertisements

Fundamental of C programming
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Alice in Action with Java Chapter 10 Flow Control in Java.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Logical Operators and Conditional statements
Chapter 4 Making Decisions
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Controlling Function Behavior Sequence, Selection and Repetition.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Selection Chapter 6. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on introduction to structures Examine if statement in more detail Study.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Calvin College Controlling Behavior The if, switch and for Statements.
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Controlling Behavior The if and for Statements. Function Behavior The behavior of a function is determined by the statements within the function. Statements.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Lecture 3 Selection Statements
Chapter 3 Selection Statements
Controlling Behavior The if and for Statements.
Chapter 3 Control Statements
CprE 185: Intro to Problem Solving (using C)
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
Chapter 4: Making Decisions.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 7 Conditional Statements
Chapter 4: Control Structures I (Selection)
The System.exit() Method
Control Structure Chapter 3.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chap 7. Advanced Control Statements in Java
Controlling Behavior The if and for Statements.
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Controlling Program Flow
Control Structure.
Presentation transcript:

More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1

Review We’ve seen that Java's if statement permits a statement to be executed selectively: if (Expression) Statement 1 [ else Statement 2 ] where expression is usually a boolean expression called a condition. From this, the Java if statement can have three different forms: 2

The Simple if The first form has no or Statement 2, and is called the simple if: The first form has no else or Statement 2, and is called the simple if: if (Condition) Statement If Condition is true, Statement is executed; otherwise Statement is skipped. Condition Statement T F 3

The Two-Branch if In the second form of if, the and Statement 2 are present: In the second form of if, the else and Statement 2 are present: if (Condition) Statement 1 else Statement 2 If Condition is true, Statement 1 is executed and Statement 2 is skipped; otherwise Statement 1 is skipped and Statement 2 is executed. Condition Statement 1 T F Statement 2 4

The Multi-branch if The if’s final form has a nested if as Statement 2 : if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2... else if (Cond N ) Stmt N else Stmt N+1 Cond 1 Stmt 1 T F Stmt 2 Cond 2 TF Stmt N Cond N TF Stmt N

Some Potential Problems 1. If x is 5, y is 6, z is 0, what value is assigned to z by: if (x > 5) if (y > 5) z = x + y; else z = x – y; 6 If this is evaluated as if (x > 5) if (y > 5) z = x + y; else z = x – y; // z = If this is evaluated as if (x > 5) if (y > 5) z = x + y; else z = x – y; // z = // z = 0

This is called the dangling-else problem and is resolved by the rule: 7 In a nested if statement, each else is matched with the nearest preceding unmatched if. If we want the else matched with the outer if, enclose the inner if in curly braces : if (x > 5) { if (y > 5) z = x + y; } else z = x – y; or give the inner if an empty else : if (x > 5) if (y > 5) z = x + y; if (x > 5) if (y > 5) z = x + y; else; else z = x – y;

2. Consider the following declarations String today = new String("Monday"), weekday = new String("Monday"), weekday = new String("Monday"), birthday = today; birthday = today; 8 What output will be produced by the following? if (today == weekday) theScreen.println("Work hard"); if (today == birthday) theScreen.println("Happy birthday"); Output: Happy birthday

today == weekday ? 0x123ae0 == 0x123ad8? No today == birthday ? 0x123ae0 == 0x123ae0? Yes 9 Monday today String objects 0x123ae0 birthday 0x123ae0 weekday 0x123ad8 Monday

Relational operators compare addresses in handles, not the values of the objects they refer to. Corollary: Classes should provide methods for comparing objects – e.g., String provides equals() and equalsIgnoreCase(), compareTo() and compareToIgnoreCase( ). if ( today.equals(weekday) ) theScreen.println("Work hard"); if ( today.equals(birthday) ) theScreen.println("Happy birthday"); Output: Work hard Happy birthday 10

Using Selection Selection is useful anytime you want to execute a statement under particular circumstances. Example: Suppose we need a method that, given the number of a day of the week (1-7), computes its corresponding name (Sunday- Saturday)? 11

Algorithm 0. Receive dayNumber. 1. If dayNumber == 1: Return "Sunday". Else if dayNumber == 2: Return "Monday". Else if dayNumber == 3: Else if dayNumber == 3: Return "Tuesday". Else if dayNumber == 4: Else if dayNumber == 4: Return "Wednesday". Else if dayNumber == 5: Else if dayNumber == 5: Return "Thursday". Else if dayNumber == 6: Else if dayNumber == 6: Return "Friday". Else if dayNumber == 7: Else if dayNumber == 7: Return "Saturday". Else Else Display an error message, and return "". 12

Coding 1 Such an algorithm can be coded using a multi-branch if: public static String dayName(int dayNumber) { if (dayNumber == 1) if (dayNumber == 1) return "Sunday"; return "Sunday"; else if (dayNumber == 2) else if (dayNumber == 2) return "Monday"; return "Monday"; else if (dayNumber == 3) else if (dayNumber == 3) return "Tuesday"; return "Tuesday"; else if (dayNumber == 4) else if (dayNumber == 4) return "Wednesday"; return "Wednesday"; else if (dayNumber == 5) else if (dayNumber == 5) return "Thursday"; return "Thursday"; else if (dayNumber == 6) else if (dayNumber == 6) return "Friday"; return "Friday"; else if (dayNumber == 7) else if (dayNumber == 7) return "Saturday"; return "Saturday"; else else { System.err.println( "\n** DayName: invalid day number"); System.err.println( "\n** DayName: invalid day number"); return ""; return ""; }} 13

Drawback The multi-branch if has non-uniform execution time: Computing "Sunday" requires comparison(s)Computing "Sunday" requires comparison(s) Computations that are "later" in the if take longer.  Computations that are "later" in the if take longer. There are situations where the time to select one of many statements must be. There are situations where the time to select one of many statements must be uniform Computing "Monday" requires comparison(s)Computing "Monday" requires comparison(s) Computing "Saturday" requires comparison(s)Computing "Saturday" requires comparison(s)7

A Solution The switch statement provides an alternative: case 3: return "Tuesday"; case 4: return "Wednesday"; case 5: return "Thursday"; case 6: return "Friday"; case 7: return "Saturday"; default: System.err.println( "\n** dayName: invalid day number"); System.err.println( "\n** dayName: invalid day number"); return ""; Need not be in order nor consecutive 15 } case 1: return "Sunday"; case 2: return "Monday"; public static String dayName(int dayNumber) public static String dayName(int dayNumber) { switch (dayNumber) {

The switch Statement The switch statement provides multi-branch selection, but guarantees uniform execution time, regardless of which branch is selected. Thus, the time to select return "Saturday"; return "Saturday"; is identical to the time to select is identical to the time to select return "Sunday"; return "Sunday"; if a switch statement is used to select them. if a switch statement is used to select them. 16

The switch Statement (ii) Pattern: Pattern: switch (Expression) { caseList 1 StatementList 1 caseList 2 StatementList 2... caseList N StatementList N default:StatementList N+1 } where expression is an integer-compatible expression, each caseList is one or more cases of this form: where expression is an integer-compatible expression, each caseList is one or more cases of this form: case ConstantValue : and each StatementList usually ends with a or statement. and each StatementList usually ends with a break or return statement. 17

Example Switch statements can use any integer-compatible type: public static double straightPercentageCutOff(char letterGrade) { switch(letterGrade) { case 'A': return 90.0; case 'B': return 80.0; case 'C': return 70.0; case 'D': return 60.0; case 'F': return 0.0; default: System.err.println(" \n** Invalid letter grade: " + letterGrade + " received by straightPercentageCutOff\n" + "-- returning 999"); return 999; } They cannot be used with or values. They cannot be used with string or double values. 18

In class example -- inverse of straightPercentageCutOff() : numeric score  letter grade 19 case 10: case 9: return 'A'; case 8: return 'B'; case 7: return 'C'; case 6: return 'D'; default: return 'F'; ( /10) public static char letterGrade(double score) { switch( (int) score ) { } }

Another Restriction if (expression == CONSTANT 1 ) {statementlist 1 } else if (expression == CONSTANT 2 ) {statementlist 2 }... else if (expression == CONSTANT n ) {statementlist n } else {statementlist n+1 } To use the switch, the common algorithm pattern is To use the switch, the common algorithm pattern is: switch (expression ) { case CONSTANT 1 : statementlist 1 case CONSTANT 2 : statementlist 2... case CONSTANT n : statementlist n default: statementlist n+1 } 20 The pattern of a switch statement used to implement it is The pattern of a switch statement used to implement it is:

Warning Switch statements exhibit drop-through behavior. 1. expression is evaluated. 2. If expression == CONSTANT i, control jumps to the statementlist i associated with CONSTANT i. 3. Control continues within the switch statement until: a. The end of the switch is reached; b. A is executed, terminating the switch; c. A is executed, terminating the method; or d. Execution is terminated, e.g., with exit(). b. A break is executed, terminating the switch; c. A return is executed, terminating the method; or d. Execution is terminated, e.g., with exit(). 21

Example What will the following display, if the value of is 4? What will the following display, if the value of dayNumber is 4? switch(dayNumber) { case 1: theScreen.print("Sunday"); case 2: theScreen.print("Monday"); case 3: theScreen.print("Tuesday"); case 4: theScreen.print("Wednesday"); case 5: theScreen.print("Thursday"); case 6: theScreen.print("Friday"); case 7: theScreen.print("Saturday"); default: theScreen.println("Error!"); } Output: 22 W ednesdayThursdayFridaySaturdayError!

Solution To avoid the "drop-though" behavior, we need to add a break (or return ) statement at the end of each case: switch(dayNumber) { case 1: theScreen.print("Sunday"); break; case 2: theScreen.print("Monday"); break; case 3: theScreen.print("Tuesday"); break; `case 4: theScreen.print("Wednesday"); break; case 5: theScreen.print("Thursday"); break; case 6: theScreen.print("Friday"); break; case 7: theScreen.print("Saturday"); break; default: theScreen.println("Error!"); } Output when is 4? Output when dayNumber is 4? 23 Wednesday

Selection: When to use switch Use the switch statement for selection when You are comparing integer-compatible types (i.e., int, long, short, char,...); and Your algorithm is of the form: if (expression == CONSTANT 1 ) statementlist 1 else if (expression == CONSTANT 2 ) statementlist 2... else if (expression == CONSTANT n ) statementlist n else statementlist n+1 24

Use the if statement when You are comparing non-integer-compatible types (i.e., double, string,...); or Your algorithm is of the more general form: if (condition 1 ) statementlist 1 else if (condition 2 ) statementlist 2... else if (condition n ) statementlist n else statementlist n+1 where the condition i don't all have the form expression == CONSTANT i with the expression the same in each condition. 25 Selection: When to use if

1. Menu: Please enter: + to add two numbers; - to subtract two numbers; * to multiple two numbers; or / to divide two numbers. --> 2. Read a choice 3. Use a(n) _________ (switch or if) statement to process the choice Example (Lab 7): switch 26

Multi-Branch Selection: Conditional Expressions where: –condition is a boolean expression –expression 1 and expression 2 are of compatible types 27 There is a ternary operator: ? :There is a ternary operator: ? : –it takes three operands Syntax:Syntax: condition ? expression 1 : expression 2

28 Example: Find the smaller of two numbers: public static int largerOf(int v1, int v2) { return (v1 > v2) ? v1 : v2; } return (v1 > v2) ? v1 : v2; } Condition Value returned if condition is true Value returned if condition is false Example: Print a date – e.g., 10/21/02, 11/01/02 theScreen.print( month + "/" + (day < 10 ? "0" : "") + day (day < 10 ? "0" : "") + day (year < 10 ? "0" : "") + year ); (year < 10 ? "0" : "") + year );

Summary Java provides two selective execution statements:Java provides two selective execution statements: –The if statement. –The switch statement. The if statement is more general and can be used to solve any problem requiring selective behavior.The if statement is more general and can be used to solve any problem requiring selective behavior. The switch is more specialized, since it can only be used in special circumstances (equality comparisons), and on certain data types (integer-compatible).The switch is more specialized, since it can only be used in special circumstances (equality comparisons), and on certain data types (integer-compatible). Java also has a ternary operator ? : used to form conditional expressions that can be used within other expressions – somewhat like putting an if statement inside an expression.Java also has a ternary operator ? : used to form conditional expressions that can be used within other expressions – somewhat like putting an if statement inside an expression. 29

Part of the Picture: Boolean Logic & Digital Design Logic circuits can be represented by boolean expressions.Logic circuits can be represented by boolean expressions. Basic axioms of Boolean algebra can be used to simplify these circuitsBasic axioms of Boolean algebra can be used to simplify these circuits 30 Arithmetic operations performed by the CPU are carried out by logic circuits made up of three basic electronic components which mimic logical operators: AND gate OR gate NOT gate (inverter)Arithmetic operations performed by the CPU are carried out by logic circuits made up of three basic electronic components which mimic logical operators: AND gate OR gate NOT gate (inverter)

Circuit Design: A Binary Half-Adder Boolean expression equivalent:Boolean expression equivalent: boolean carry = digit1 && digit2, sum = (digit1 || digit2) && !(digit1 && digit2); sum = (digit1 || digit2) && !(digit1 && digit2); digit1digit2carrysum Truth tableTruth table 0 = false 1 = true

Digital circuit equivalent:Digital circuit equivalent: Note binary half-adder class, source code, Figure 7.9, test driver Figure boolean carry = digit1 && digit2, sum = (digit1 || digit2) && !(digit1 && digit2); digit 1 digit 2 sum carry