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

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Logic & program control part 3: Compound selection structures.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
True or false A variable of type char can hold the value 301. ( F )
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
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.
Multi-alternative Selection Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
C++ for Engineers and Scientists Third Edition
Control Structures I (Selection)
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 4 Selection Structures: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Flow of Control Part 1: Selection
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement(s); // optional.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Chapter 05 (Part III) Control Statements: Part II.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
C++ Programming Control Structures I (Selection).
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Chapter 3 Control Statements
Selections Java.
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Additional Control Structures
Chapter 7 Additional Control Structures
3 Control Statements:.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Presentation transcript:

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

CSE B-2 Topics Comparing –Floating point numbers –Objects –Strings Conditional Operator

CSE B-3 Comparing Floating-Point Numbers With IEEE 754 floating-point representation, minor rounding errors can occur in calculations We compute 11 *.1 two ways 1. Multiplying 11 *.1, the result is Adding.1 11 times, the result is … These values will not compare as equal using the equality operator ( == ) We get similar results when assigning the same value to a float variable and to a double variable, then comparing the values.

CSE B-4 // Part 1: Compute 11 *.1 two ways double d1 =.0; // add.1 to 0 eleven times d1 +=.1; // 1 d1 +=.1; // 2 d1 +=.1; // 3 d1 +=.1; // 4 d1 +=.1; // 5 d1 +=.1; // 6 d1 +=.1; // 7 d1 +=.1; // 8 d1 +=.1; // 9 d1 +=.1; // 10 d1 +=.1; // 11 double d2 =.1 * 11; // compute 11 *.1 C.O.Wln( "d1 = " + d1 ); C.O.Wln( "d2 = " + d2 ); if ( d1 == d2 ) C.O.Wln( "d1 and d2 are equal" ); else C.O.Wln( "d1 and d2 are not equal" ); // Part 2: Compare float and double with same value float piF = f; double piD = ; C.O.Wln( "\npiF = " + piF ); C.O.Wln( "pid = " + piD ); if ( piF == piD ) C.O.Wln( "piF and piD are equal" ); else C.O.Wln( "piF and piD are not equal" );

CSE B-5 Output d1 = d2 = 1.1 d1 and d2 are not equal piF = pid = piF and piD are not equal

CSE B-6 Solution Choose a small threshold value -- how close should the values be to be considered equal? If the difference between the two values is less than the threshold value, then we will consider the two floating-point numbers to be equal. Hint: use the Math.Abs method to compute the difference.

CSE B-7 // Part 1: Same as last example C.O.Wln( "d1 = " + d1 ); C.O.Wln( "d2 = " + d2 ); if ( Math.abs( d1 - d2 ) <.0001 ) C.O.Wln( "d1 and d2 are considered equal" ); else C.O.Wln( "d1 and d2 are not equal" ); // Part 2: Compare float and double with same value float piF = f; double piD = ; C.O.Wln( "\npiF = " + piF ); C.O.Wln( "piD = " + piD ); if ( Math.abs( piF - piD ) <.0001 ) C.O.Wln( "piF and piD are considered equal" ); else C.O.Wln( "piF and piD are not equal" );

CSE B-8 Output d1 = d2 = 1.1 d1 and d2 are considered equal piF = pid = piF and piD are considered equal

CSE B-9 Comparing Floats Problematic given rounding/precision Pick a tolerance, and if the difference between the numbers is less than this tolerance, consider the numbers equivalent if ( Math.abs( d1 - d2 ) < THRESHOLD) C.WL("d1 and d2 are considered equal"); else C.WL("d1 and d2 are not equal");

CSE B-10 Comparing Characters What does it mean to “compare” 2 characters? Is ‘a’ < ‘b’? Is ‘A’ > ‘z’?

CSE B-11 Lexicographic Ordering Because all characters are “encoded” using the Unicode encoding scheme, Unicode values are compared. Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed

CSE B-12 Comparing Objects The equality operator ( == ) compares object references. Example: –If d1 and d2 are two Date object references, then ( d1 == d2 ) evaluates to true only if d1 and d2 point to the same object, that is, the same memory location. –The equality operator does not compare the data (month, day, and year) in those objects.

CSE B-13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-13 Comparing Object Data With d1 and d2 Date object references: d1.equals(d2); Returns true if the month, day, and year of d1 equals the month, day, and year of d2. Return type Method name and argument list booleanequals( Object obj ) returns true if the data of the object obj is equal to the data in the object used to call the method

CSE B-14 // instantiate two Date objects with identical data Date d1 = new Date( 4, 10, 2006 ); Date d2 = new Date( 4, 10, 2006 ); // assign object reference d1 to d3 Date d3 = d1; // d3 now points to d1 // instantiate another object with different data Date d4 = new Date( 12, 1, 2006 ); Do not use the equality operators ( ==, != ) to compare object data; instead, use the equals method.

CSE B-15 Comparing Date Objects

CSE B-16 // compare references using equality operator if ( d1 == d2 ) C.WL( "d1 and d2 are equal\n" ); else C.WL( "d1 and d2 are not equal\n" ); if ( d1 == d3 ) C.WL( "d1 and d3 are equal\n" ); else C.WL( "d1 and d3 are not equal\n" ); // compare object data using the equals method if ( d1.equals( d2 ) ) C.WL( "d1 data and d2 data are equal\n" ); else C.WL( "d1 data and d2 data are not equal\n" ); if ( d1.equals( d4 ) ) C.WL( "d1 data and d4 data are equal" ); else C.WL( "d1 data and d4 data are not equal" ); Bad Good

CSE B-17 The Conditional Operator (?:) The conditional operator ( ?: ) contributes one of two values to an expression based on the value of the condition. Some uses are –handling invalid input –outputting similar messages. Syntax: ( condition ? trueExp : falseExp ) If condition is true, trueExp is used in the expression If condition is false, falseExp is used in the expression

CSE B-18 Equivalent Code The following statement stores the absolute value of the integer a into the integer absValue. int absValue = ( a > 0 ? a : -a ); The equivalent statements using if/else are: int absValue; if ( a > 0 ) absValue = a; else absValue = -a;

CSE B-19 The Conditional Operator Another example: C.O.Wln ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed

CSE B-20 Nested if Statements if statements can be written as part of the true or false block of another if statement. Typically, you nest if statements when more information is required beyond the results of the first if condition The compiler matches any else clause with the most previous if statement that doesn't already have an else clause. You can use curly braces to force a desired if/else pairing.

CSE B-21 Example if ( x == 2 ) if ( y == x ) C.O.Wln( "x and y equal 2" ); else C.O.Wln( "x equals 2 but y does not" ) ; The else clause is paired with the second if, that is: if ( y == x )

CSE B-22 Another Example if ( x == 2 ) { if ( y == x ) C.O.Wln( "x and y equal 2" ); } else C.O.Wln( "x does not equal 2" ); With curly braces added, the else clause is paired with the first if, that is: if ( x == 2 )

CSE B-23 The "Dangling else" A dangling else is an else clause that cannot be paired with an if condition if ( x == 2 ) if ( y == x ) C.O.Wln( "x and y equal 2" ); else // paired with ( y == x ) C.O.Wln( "y does not equal 2" ); else // paired with ( x == 2 ) C.O.Wln( "x does not equal 2" ); else // no matching if! C.O.Wln( "x and y are not equal" ); Generates the compiler error: 'else' without 'if'

CSE B-24 In the absence of braces, an else is always paired with the closest preceding if that doesn’t already have an else paired with it.

CSE B-25 Bad Example has output: FAIL float average; average = 100.0; if ( average >= 60.0 ) if ( average < 70.0 ) C.O.Wln( “ Marginal PASS ” ); else C.O.Wln( “ FAIL ” ); WHY? The compiler ignores indentation and pairs the else with the second if. average 100.0

CSE B-26 To correct the problem, use braces float average; average = 100.0; if ( average >= 60.0 ) { if ( average < 70.0 ) C.O.Wln( “ Marginal PASS ” ); } else C.O.Wln( “ FAIL ” ); average 100.0

CSE B-27 The switch Statement Sometimes the switch statement can be used instead of an if/else/if statement for selection. Requirements: – we must be comparing the value of a character (char) or integer (byte, short, or int) expression to constants of the same types

CSE B-28 Syntax of switch switch ( char or integer expression ) { case constant1: // statement(s); break; // optional case constant2: // statement(s); break; // optional … default: // optional statement(s); … }

CSE B-29 Operation of switch The expression is evaluated, then its value is compared to the case constants in order. When a match is found, the statements under that case constant are executed in sequence until either a break statement or the end of the switch block is reached. Once a match is found, if other case constants are encountered before a break statement, then the statements for these case constants are also executed.

CSE B-30 Some Finer Points of switch The break statements are required. Their job is to terminate execution of the switch statement. The default label and its statements are optional. They are executed when the value of the expression does not match any of the case constants. The statements under the case constant are also optional, so multiple case constants can be written in sequence if identical operations will be performed for those values. You cannot perform relational checks with a switch statement

CSE B-31 Example: a Simple Calculator Prompt user for two doubles (num1, num2) and a char (operation), which can be 'a' for addition or 's' for subtraction switch ( operation ) { case 'a': result = num1 + num2; break; case 's': result = num1 - num2; break; }

CSE B-32 A Case-Insensitive Calculator switch ( operation ) { case 'a': case 'A': result = num1 + num2; break; case 's': case 'S': result = num1 - num2; break; }

CSE B-33 float weightInPounds = f; char weightUnit ;... // user enters letter for desired weightUnit switch ( weightUnit ) { case ‘P’ : case ‘p’ : C.O.Wln(weightInPounds + “ pounds “ ) ; break ; case ‘O’ : case ‘o’ : C.O.Wln(16.0 * weightInPounds + “ ounces “ ) ; break ; case ‘K’ : case ‘k’ : C.O.Wln(weightInPounds / “ kilos “ ) ; break ; case ‘G’ : case ‘g’ : C.O.Wln(454.0 * weightInPounds + “ grams “ ) ; break ; default : C.O.Wln(“That unit is not handled! “ ) ; break ; }

CSE B-34 More Examples // Determine average life expectancy of a standard light bulb. switch (watts) { case 25:life = 2500; break; case 40: case 60:life = 1000; break; case 75: case 100:life = 750; break; default:life = 0; }// end switch C.O.Wln( “ Life expectancy of “ + watts + “ -watt bulb: “ + watts );

CSE B-35 Use Switch for Menus switch (edit_op) { case ‘ D ’ : case ‘ d ’ :// Delete a substring doc.do_delete (text_string); break; case ‘ F ’ : case ’ f ’ : // Find a substring doc.do_find (text_string);break; case ‘ I ’ : case ‘ i ’ : // Insert a substring doc.do_insert (text_string);break; case ‘ R ’ : case ‘ r ’ : // Replace a substring doc.do_replace (text_string);break; case ‘ Q ’ : case ‘ q ’ :// Quit C.O.Wln( “ Quitting text editor pgm! ” ); break; default: C.O.Wln( “ Invalid edit code entered. ” ); } // end switch;

CSE B-36 Now It’s Your Turn Time for some group work!!!

CSE B-37 Write an expression for each age is from 18 to 21 inclusive. water is less than 1.5 and is also greater than 0.1. year is divisible by 4 speed is not greater than 55. Write a logical assignment statement for each of the following: assign a value of true to between if n is in the range of - k to + k, inclusive; otherwise assign a value of false. assign a value of true to uppercase is ch is an uppercase letter; otherwise, assign a value of false. assign a value of true to divisor if m is a divisor of n ; otherwise assign a value of false.

CSE B-38 Write If-Then or If-Then-Else for each If taxCode is ‘ T ’, increase price by adding taxRate times price to it. If code has value 1, calculate and display taxDue as the product of income and taxrate. If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A.

CSE B-39 Some Answers if (taxCode == ‘ T ’ ) price = price + taxRate * price ; if ( code == 1) { taxDue = income * taxRate; C.O.Wln(taxDue); }

CSE B-40 Remaining Answer if ( ( A > 0 ) && (A < 5) ) B = 1/A; else B = A;

CSE B-41 What’s the output? and Why? int age; age = 20; if ( age = 16 ) { C.O.Wln(“Did you get driver’s license?”) ; }

CSE B-42 What’s the output? and Why? int age; age = 30; if ( age < 18 ) C.O.Wln(“Do you drive?”); C.O.Wln(“Too young to vote”);

CSE B-43 What’s the output? and Why? boolean code; code = false; if ( ! code ) C.O.Wln(“Yesterday”); else C.O.Wln(“Tomorrow”);

CSE B-44 What’s the output? and Why? if (x > y) x = x ; C.O.Wln(“x bigger” ); else C.O.Wln(“x smaller” ); C.O.Wln(“y is “ + y );