1 Conditions, logical expressions, and selection Introduction to control structures.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Logic & program control part 2: Simple selection structures.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
1 Chapter 5 Branching and Method Algorithm Design.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
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 (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Flow of Control is Sequential unless a “control structure” is used to change that there are 2 general types of control structures: Selection (also called.
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Conditions, logical expressions, and selection Introduction to control structures.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
1 Chapter 4 Selection and Encapsulation. 2 Chapter 4 Topics l Java Control Structures l boolean Data Type l Using Relational and Logical Operators in.
Logical Operators and Conditional statements
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Control Structures I (Selection)
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Conditions, Logical Expressions, and Selection Control Structures Sumber dari :
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Flow of Control There are 5 general types of Java control structures: Sequence (by default) Selection (also called branch or decision) Loop (also called.
Flow of Control Part 1: Selection
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
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.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
1 Conditions, Logical Expressions, and Selection Control Structures.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
BOOLEAN OPERATIONS AND CONDITIONALS CHAPTER 20 1.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
C++ Programming Control Structures I (Selection).
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 3 Edited by JJ Shepherd
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Branching Statements
Boolean Expressions and If
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Chapter 4: Control Structures I (Selection)
Controlling Program Flow
Boolean Expressions September 1, 2019 ICS102: The course.
Presentation transcript:

1 Conditions, logical expressions, and selection Introduction to control structures

2 Flow of control In a program, statements execute in a particular order sequentiallyBy default, statements are executed sequentially: –One after another, from top to bottom –One at a time –Exactly once control structuresThis sequential flow of control can be altered through the use of control structures

3 Control structures There are two general types of control structures: –Selection (aka branching) structures: cause flow of control to take, or not take, a particular direction –Repetition (aka iteration, looping) structures: cause a set of statements to execute several times Both of these type of structures depend on the evaluation of logical expressions

4 Logical expressions booleanLogical expressions evaluate to true or false; the result of a logical expression is always a value of data type boolean Most logical expressions use relational and logical operators In Java the form of a simple logical expression is: Operand1operatorOperand2 –The operands can be simple or compound expressions of any type –The operator is a relational operator

5 Relational operators The relational operators in Java include: <: is less than <=:is less than or equal to ==:equals >:is greater than >=:is greater than or equal to !=:does not equal

6 Logical expression examples Suppose you had the following declarations: int x = 3, y = 7; Then the following expressions would have the values indicated: x > y // (false) y >= x // (true) x != y // (true) (x > y) == true // (false) ((y >= x) == (x != y)) // true x = y // value is 7; not a logical expression

7 Logical expressions & floating-point numbers In general, it isn’t a good idea to compare two floating-point numbers for equality This is because floats and doubles always represent approximations of values, and, although 2 equals 2, does not equal A better method for comparing floating- point numbers involves deciding how close is close enough to equal

8 Comparing floating-point numbers for equality The expression below assumes numbers are close enough to equal if they are within 1/100,000,000 of one another: Math.abs(a-b) < 1.0e-10 Notes: –“Math.abs” is the absolute value function –The expression is true if the absolute value of the difference between variable a and b is less than

9 Comparing Objects When comparing primitive-type variables, constants, and values, the relational operators are adequate When comparing objects, we can use the relational operators, but they don’t mean the same thing they mean with the primitive types

10 Comparing Objects Recall that, when we declare an object, the identifier in the declaration doesn’t contain an object until we initialize it by calling the object’s constructor (using the new operator) When we invoke the constructor, a new object is created, and its memory address is associated with the identifier from the declaration

11 Example 1 JFrame w1, w2;// declares 2 window objects w1 = new JFrame();// creates a new window w2 = new JFrame();// creates a 2 nd window In the code above, w1 and w2 are assigned the addresses of 2 different window objects Although the two new windows are identical, it is intuitively obvious that they are not the same window What happens if we compare them for equality?

12 Example 1 continued The expression w1 == w2 will evaluate to false The reason for this is, we are not really comparing the two window objects (which should be identical) Instead, we’re comparing their addresses – since each has its own address, and each address is unique, the comparison evaluates false

13 Example 2 JFrame w1, w2;// declares 2 window objects w1 = new JFrame();// creates new object w2 = w1;// assigns address of object to 2 nd variable In this example, only one window object has been created The expression w1 == w2 evaluates to true, because both object variables refer to the same object

14 Comparing objects: method equals Because the relational operator == compares only the addresses of objects, many objects have a member method to compare object contents for equality The equals method performs a comparison that depends on its definition within the class For example, for String objects, the equals method performs a letter-by-letter comparison between two Strings, evaluating true if the Strings’ contents are identical

15 Example 3: comparing Strings String s1, s2; s1 = new String (“a string”); s2 = new String (“a string”); The expression s1 == s2 evaluates false The expressions s1.equals(s2) and s2.equals(s1) evaluate true

16 More String comparison methods The equals method returns true if the calling object and its argument are identical in both spelling and case A second method, equalsIgnoreCase, can be used to compare Strings for spelling only; for example: String s1 = new String (“hello”); String s2 = new String (“HELLO”); –s1.equals(s2) returns false –s1.equalsIgnoreCase(s2) returns true

17 More String comparison methods The String class includes two comparison methods besides equals and equalsIgnoreCase: –compareTo is similar to equals; it is case- sensitive –compareToIgnoreCase, as the name implies, ignores case

18 String compare methods Both compare methods work as follows: –if the calling object is less than the argument, the method returns a negative number –if the calling object is greater than the argument, the method returns a positive number (greater than 0) –if the Strings are equal, the method returns 0 In this context, “less than” and “greater than” refer to alphabetical order – so, for example, “abc” is less than “bcd” because “a” comes before (is less than) “b”

19 String compare methods If the case-sensitive compare method is used, then if two Strings have the same spelling but one contains capital letters, the one with the capital letters will evaluate as less than the one with equivalent lowercase letters So, for example, “Hello” is less than “hello”

20 Exception to the rules One important point about Strings – they can sometimes act like primitive objects If a String is instantiated without the new operator, as in the example below: String s1 = “no news is good news”; String s2 = “no news is good news”; –then the expression s1 == s2 evaluates true –this is because, if the same String literal is assigned without “new” to 2 different objects, both objects refer to the same memory location –however, if s1 then gets assigned a different String literal, the expression s1 == s2 will be false, because now s2 refers to the original address, but s1 now refers to a new address

21 Logical operators Three operators in Java can be used to form compound logical expressions (expressions that combine simple logical, or relational expressions) They are: && - logical and || - logical or ! – logical not

22 Logical operators Logical and (&&) combines two expressions; if both sub-expressions are true, then the compound expression is true – otherwise, the compound expression is false Logical or also combines two expressions; the compound expression is true if one or both sub- expressions is true, false otherwise Logical not reverses the truth value of an expression; if the original expression was true, not makes it false, and vice versa

23 Truth table Graphical display of relationships between truth values of propositions Shows all possible values of propositions, or combinations of propositions Suppose p represents an expression; then the truth table for !p is as show below: p!p T F F T

24 Truth table for p && q pq p && q TT T TF F FT F FF F Suppose p and q represent two logical sub-expressions; then the compound expression p && q has the following truth table:

25 Truth table for p || q pq p || q TT T TF T FT T FF F Suppose p and q represent two logical sub-expressions; then the compound expression p || q has the following truth table:

26 OperatorMeaning Associativity ! NOTRight *, /, % Multiplication, Division, Modulus Left +, - Addition, SubtractionLeft < Less thanLeft <= Less than or equal toLeft > Greater thanLeft >= Greater than or equal toLeft == Is equal toLeft != Is not equal to Left && ANDLeft || OR Left = AssignmentRight Partial listing of operator precedence in Java – more complete list, p 241 of Wu

27 int age ; boolean isSenior, hasFever ; double temperature ; age = 20; temperature = 102.0; isSenior = (age >= 55) ; hasFever = (temperature > 98.6) ; EXPRESSIONVALUE isSenior && hasFever false isSenior || hasFever true ! isSeniortrue ! hasFeverfalse

28 What is the value? int age, height; age = 25; height = 70; EXPRESSIONVALUE ! (age < 10) ? ! (height > 60) ?

29 “Short-Circuit” Evaluation Java uses short circuit evaluation of logical expressions This means logical expressions are evaluated left to right and evaluation stops as soon as the final truth value can be determined

30 Short-Circuit Example int age, height; age = 25; height = 70; EXPRESSION (age > 50) && (height > 60) false Evaluation can stop now because result of && is only true when both sides are true. It is already determined that the entire expression will be false.

31 More Short-Circuiting int age, height; age = 25; height = 70; EXPRESSION (height > 60) || (age > 40) true Evaluation can stop now because result of || is true if one side is true. It is already determined that the entire expression will be true.

32 What happens? int age, weight; age = 25; weight = 145; EXPRESSION (weight = 20) true Must still be evaluated because truth value of entire expression is not yet known. Why? Result of && is only true if both sides are true.

33 What happens? int age, height; age = 25; height = 70; EXPRESSION ! (height > 60) || (age > 50) true false Does this part need to be evaluated?

34 Write an expression for each taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22

35 Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What happens if Number has value 0?

36 Short-Circuit Benefits one boolean expression can be placed first to “guard” a potentially unsafe operation in a second boolean expression Time is saved in evaluation of complex expressions using operators || and &&

37 Our Example Revisited int number; float x; ( number ! = 0) && ( x < 1 / number ) is evaluated first and has value false Because operator is &&, the entire expression will have value false. Due to short-circuiting the right side is not evaluated in Java.

38 Summary of logical expressions in Java “boolean expression” means an expression whose value is true or false An expression is any valid combination of operators and operands Use of parentheses is encouraged; otherwise, use precedence chart to determine order

39 Logical expressions & program control Relational expressions can be used to control the flow of logic in a program Depending on the truth value of an expression, a program can be made to perform one task or another (but not both) A control structure that fits this description is called a selection structure

40 Selection & Java if statementIn Java, a simple selection structure is created using an if statement, which has the following syntax: if (relational expression) { statement(s); } If only one statement follows the if clause, the curly brackets are unnecessary

41 Payroll example in Java double otpay = 0.0;// overtime pay – time and 1/2 if (hours > 40) { otpay = hours – 40; otpay = otpay * wage * 1.5; } pay = otpay + hours * wage;

42 What can go wrong here? float average;// average price float total;// sum of prices // entered int howMany;// number of // prices entered... average = total / howMany;

43 Improved Version float average,// average price total;// sum of prices entered int howMany;// number of prices entered … if ( howMany > 0 ) { average = total / howMany; }

44 The if-else control structure In the previous examples, a set of statements either executed, or didn’t, based on the truth value of an expression In many situations, two options make more sense – one set of statements executes if the condition is true, while the other executes if it is false This slightly more complicated version is called an if/else structure

45 If/else in Java Basic syntax is: if (relational expression) { statement(s); } else { statement(s) }

46 Example Read an int value from the keyboard If value is less than 0, print its square If value is greater than 0, print its square root

47 Program logic in Java String s; double value; s=JOptionPane.showInputDialog(null, “Enter a number”); value = Double.parseDouble(s); if (value < 0) JOptionPane.showMessageDialog(null, “Value squared is ” + Math.pow(value, 2.0)); else JOptionPane.showMessageDialog(null, “Square root of value is: ” + Math.sqrt(value));

48 Use of blocks recommended if ( Expression ) { } else { } “if clause” “else clause”

49 What output? and Why? boolean code; code = false; if ( ! code ) cout << “Yesterday”; else cout << “Tomorrow”;

50 int carDoors, driverAge ; double premium, monthlyPayment ;... if ( (carDoors == 4 ) && (driverAge > 24) ) { System.out.println(“LOW RISK”) ; premium = ; } else { System.out.println(“HIGH RISK”) ; premium = ; } monthlyPayment = premium / ;

51 What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) System.out.println(“LOW RISK”) ; premium = ; else System.out.println(“HIGH RISK”) ; premium = ; monthlyPayment = premium / ; COMPILE ERROR OCCURS. The “if clause” is the single statement following the if.

52 Adding braces: if ( (carDoors == 4 ) && (driverAge > 24) ) { System.out.println(“LOW RISK”) ; premium = ; } else System.out.println(“HIGH RISK”) ; premium = ; monthlyPayment = premium / ; PROGRAM COMPILES. Is it correct?

53 Write If or If-Else for each If taxCode is 1, increase price by adding taxRate times price to it. If code has value 1, read values for income and taxRate from the keyboard, and calculate and display taxDue as their product. If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A.

54 The ternary operator As an alternative to the simple if/else structure, Java offers a shortcut: the ternary operator “ternary” refers to the fact that the operator takes three operands The symbol for the ternary operator is ?:

55 The ternary operator The ternary operator takes the following form: expression1 ? expression2 : expression3 –if expression1 is true, expression2 is evaluated; if expression 1 is false, expression3 is evaluated –the result of the entire ?: expression is the value of whichever expression (2 or 3) was evaluated

56 Example code using ?: (value < 0) ? value = Math.pow(value, 2.0) : value = Math.sqrt(value); Note there is no semicolon after the first expression. That is because this is not the end of the instruction. Instead, the colon indicates the end of the “if” clause.

57 Conditions, logical expressions, and selection Introduction to control structures