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
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
Advertisements

1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common 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 © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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.
Chapter 4 Making Decisions
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
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
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
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.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
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.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
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.
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.
A First Book of C++ Chapter 4 Selection.
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
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Chapter 7 Conditional Statements
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Control Structure Chapter 3.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
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 = _____

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 ________________ : if (x > 5) if (y > 5) z = x + y; else z = x – y; if (x > 5) __ if (y > 5) z = x + y; __ else z = x – y; or give the inner if an _______________: if (x > 5) if (y > 5) z = x + y; else z = x – y; if (x > 5) if (y > 5) z = x + y; ___________ else z = x – y;

2. Consider the following declarations String today = new String("Monday"), weekday = new String("Monday"), 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:

today == weekday ? 0x123ae0 == 0x123ad8? ______ today == birthday ? 0x123ae0 == 0x123ae0? ______ 9 Monday today String objects birthday weekday 0x123ae0 0x123ad8 0x123ae0 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 birhday"); Output: 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

13 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 ""; }} Coding 1

Drawback The multi-branch if has ______________execution time: Computing "Sunday" requires ___ comparison(s)Computing "Sunday" requires ___ comparison(s) Computing "Monday" requires ___ comparison(s)Computing "Monday" requires ___ comparison(s) Computing "Saturday" requires ___ comparison(s)Computing "Saturday" 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 ________________. 14

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

The switch Statement The switch statement provides multi-branch selection, but guarantees __________________________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: switch (Expression) { caseList 1 StatementList 1 caseList 2 StatementList 2... caseList N StatementList N default: StatementList N+1 } where Expression is an ______________-compatible expression, each caseList is one or more cases of this form: case ConstantValue : and each StatementList usually ends with a ___________ or____________ statement. 17

Example They ________________ with or values. They ________________ with string or double values. 18 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; }

In class example -- inverse of straightPercentageCutOff() : numeric score  letter grade 19 public static char letterGrade(double score) { }

Another Restriction if (expression == CONSTANT1 ) {statementlist1} else if (expression == CONSTANT2 ) {statementlist2}... else if (expression == CONSTANTn ) {statementlistn} else {statementlistn+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 C++ switch statements exhibit ________________ behavior. 1. expression is evaluated. 2. If expression == CONSTANT i, control jumps to the statementlist i associated with CONSTANT i. 3. Control ____________within the switch statement until: a. The end of the switch is reached; b. A is executed, terminating the switch; b. A break is executed, terminating the switch; c. A is executed, terminating the function; or c. A return is executed, terminating the function; 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

Solution To avoid the "drop-though" behavior, we need to add __________________________: __________________________ at the end of each case: switch(dayNumber) { case 1: cout << "Sunday"; ___________ case 2: cout << "Monday"; ___________ case 3: cout << "Tuesday"; ___________ case 4: cout << "Wednesday"; break; case 5: cout << "Thursday"; break; case 6: cout << "Friday"; break; case 7: cout << "Saturday"; break; default: cout << "Error!" << endl; } Output when is 4: Output when dayNumber is 4: 23

Selection: When to use switch 24 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

25 Selection: When to use if 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.

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): 26

Multi-Branch Selection: Conditional Expressions where: –condition is a boolean expression –expression 1 and expression 2 are of compatible types 27 Thereis a ___________ operator: _____Thereis a ___________ operator: _____ –it takes operands –it takes __________ 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 _________ ________ _________; return _________ ________ _________;} 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 _______________________ + day ________________________+ year ); ________________________+ 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 circuits.Basic 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 carry = digit1 && digit2, sum = (digit1 || digit2) && !(digit1 && digit2);Boolean expression equivalent: boolean carry = digit1 && digit2, sum = (digit1 || digit2) && !(digit1 && digit2); digit1digit2carrysum Truth tableTruth table

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