Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)



Similar documents
Boolean Logic in MATLAB

Welcome to Basic Math Skills!

Mathematical Induction

Chapter 5. Selection 5-1

26 Integers: Multiplication, Division, and Order

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

0.1 Dividing Fractions

1 Description of The Simpletron

3. Mathematical Induction

hp calculators HP 17bII+ Net Present Value and Internal Rate of Return Cash Flow Zero A Series of Cash Flows What Net Present Value Is

Preparing cash budgets

Unit 7 The Number System: Multiplying and Dividing Integers

Independent samples t-test. Dr. Tom Pierce Radford University

Playing with Numbers

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Borrowing Money Standard 7 Assessment

Working with whole numbers

Negative Integral Exponents. If x is nonzero, the reciprocal of x is written as 1 x. For example, the reciprocal of 23 is written as 2

Personal Financial Manager (PFM) FAQ s

Click on the links below to jump directly to the relevant section

Using Proportions to Solve Percent Problems I

Investment Appraisal INTRODUCTION

7 Literal Equations and

Pre-Algebra Lecture 6

How To Proofread

Using Casio Graphics Calculators

Binary Adders: Half Adders and Full Adders

OA3-10 Patterns in Addition Tables

Fraction Problems. Figure 1: Five Rectangular Plots of Land

Reading 13 : Finite State Automata and Regular Expressions

WRITING PROOFS. Christopher Heil Georgia Institute of Technology

6.080/6.089 GITCS Feb 12, Lecture 3

SO-03 Sales Order Processing Administration

if and if-else: Part 1

It Is In Your Interest

Creating Basic Excel Formulas

Chapter 11 Number Theory

Writing Thesis Defense Papers

Part 1 Expressions, Equations, and Inequalities: Simplifying and Solving

SHELL INDUSTRIAL APTITUDE BATTERY PREPARATION GUIDE

Conditional Statements Summer 2010 Margaret Reid-Miller

Chapter One Introduction to Programming

Sage 50 Accounts Construction Industry Scheme (CIS)

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

Closing The Sale. What actually happens during the sales process is that the salesperson:

Teaching & Learning Plans. Arithmetic Sequences. Leaving Certificate Syllabus

ACADEMIC TECHNOLOGY SUPPORT

Integrated Accounting System for Mac OS X


Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Counting Money and Making Change Grade Two

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

Teaching & Learning Plans. Introduction to Equations. Junior Certificate Syllabus

CHAPTER 18 Programming Your App to Make Decisions: Conditional Blocks

Mind on Statistics. Chapter 12

8 Primes and Modular Arithmetic

- User input includes typing on the keyboard, clicking of a mouse, tapping or swiping a touch screen device, etc.

2.6 Exponents and Order of Operations

**Unedited Draft** Arithmetic Revisited Lesson 4: Part 3: Multiplying Mixed Numbers

2: Entering Data. Open SPSS and follow along as your read this description.

Improved VAT in QuickBooks 2008 & Later

Percentages. You will need a calculator 20% =

Introduction to Java

ECON 459 Game Theory. Lecture Notes Auctions. Luca Anderlini Spring 2015

Sources: On the Web: Slides will be available on:

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Simple Regression Theory II 2010 Samuel L. Baker

Clock Arithmetic and Modular Systems Clock Arithmetic The introduction to Chapter 4 described a mathematical system

Elasticity. I. What is Elasticity?

J a v a Quiz (Unit 3, Test 0 Practice)

LINEAR INEQUALITIES. less than, < 2x + 5 x 3 less than or equal to, greater than, > 3x 2 x 6 greater than or equal to,

SAT Math Facts & Formulas Review Quiz

Moving from CS 61A Scheme to CS 61B Java

Life Insurance Buyer's Guide

Accentuate the Negative: Homework Examples from ACE

Lecture 2 Notes: Flow of Control

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

File by OCR Manual. Updated December 9, 2008

Sales Training Programme. Module 8. Closing the sale workbook

2007 Choosing a Medigap Policy:

Lesson 8 Setting Healthy Eating & Physical Activity Goals

A-level COMPUTER SCIENCE

Chapter 8: Fundamentals of Capital Budgeting

what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored?

Common Data Structures

Adding Integers Using a Number Line

Programming Your App to Make Decisions: Conditional Blocks

Lecture Notes on Linear Search

Pseudo code Tutorial and Exercises Teacher s Version

The fundamental question in economics is 2. Consumer Preferences

User guide for the Error & Warning LabVIEW toolset

Quosal Form Designer Training Documentation

Integers, I, is a set of numbers that include positive and negative numbers and zero.

Integrated Invoicing and Debt Management System for Mac OS X

The Easy Picture Guide to banking xxxx. Choosing xxxxxxxxxxxxxxxxxxxxx a xxxxxxxxxxxxxxxxxxxxx. bank account

Your guide to Using a solicitor

Informatica e Sistemi in Tempo Reale

PREPARATION MATERIAL FOR THE GRADUATE RECORD EXAMINATION (GRE)

Handout #1: Mathematical Reasoning

Transcription:

Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08) The if statements of the previous chapters ask simple questions such as count<10. Often simple questions are not enough. This chapter discusses ways to ask more complicated questions. Chapter Topics: Relational Operators (review) Logical Operators AND Operator How to check that a number is in range Boolean Expressions OR Operator Comparison between AND and OR NOT Operator Questions involving boolean expressions have been prominent on past AP Computer Science Tests. QUESTION 1: You have decided to bake some cookies (much cheaper than buying them at the Mall). An interesting cookie recipe calls for 4 cups of flour and 2 cups of sugar. You look in your pantry and find 3 cups of flour and 2 cups of sugar. Can you bake cookies with what you have? Used by permission. Page 1 of 29

No. You have enough sugar, but not enough flour, so you can't follow the recipe. Both Items Needed The question about whether you have enough ingredients has two parts: You need at least 4 cups of flour AND You need at least 2 cups of sugar Since you do not have enough flour, you don't have enough ingredients. QUESTION 2: What if you had 9 cups of flour and 1 cup of sugar. Now could you follow the recipe? Used by permission. Page 2 of 29

No. You need 4 cups of flour and 2 cups of sugar. Now you have more than enough flour, but not enough sugar, so you can't follow the recipe. Cookie Calculator In order to bake cookies two things must be : You must have 4 or more cups of flour. You must have 2 or more cups of sugar. If just one of these is false, then you do not have enough ingredients. Here is a simulation of the cookie program. Enter some values for sugar and flour and see if you can bake cookies. Use only integers as input. http://chortle.ccsu.edu/java5/notes/chap14/ch14_3.html The symbol && means AND. The if statement asks a question with two parts: if ( flour >= 4 && sugar >= 2 ) ---------- ---------- flour part sugar part Each part is a relational expression. A relational expression uses a relational operator to compute a or false value. The entire expression between parentheses is also a boolean expression. A boolean expression is often composed of smaller boolean expressions. This is similar to human language where compound sentences are made from smaller sentences. QUESTION 3: Say that you enter 9 for flour and 1 for sugar. What value ( or false) does each part give you? Used by permission. Page 3 of 29

flour >= 4 sugar >= 2 false Examine this part of the program: && // check that there is enough of both ingredients if ( flour >= 4 && sugar >= 2 ) System.out.println("Enough for cookies!" ); else System.out.println("sorry..." ); For you to have enough ingredients, both relational expressions must be. This is the role of the && (and-operator) between the two relational expressions. The && requires that both flour >= 4 and sugar >= 2 are before the entire expression is. The entire question must be in order for the branch to execute. The and operator && is a logical operator. A logical operator examines two /false values and outputs a single /false value. QUESTION 4: What is printed if the user enters 6 for flour and 4 for sugar? Used by permission. Page 4 of 29

How much flour do you have? 6 How much sugar do you have? 4 Enough for cookies! When execution gets to the if statement, it finds that flour >= 4 is, because 6 >= 4 and sugar >= 2 is, because 4 >= 2 Both sides are, so AND gives. AND Operator The and operator requires that both sides are : this side must be && this side must be If both sides are, the entire expression is. If either side (or both) are false, the entire expression is false. && is a logical operator because it combines two /false values into a single /false value. Here is what && does: && = false && = false && false = false false && false = false Use and when every requirement must be met. QUESTION 5: Look at the boolean expression: flour >= 4 && sugar >= 2 What will the expression give us if flour is 2 and sugar is 0? Used by permission. Page 5 of 29

The whole expression will be false, because && combines two falses into false. flour >= 4 && sugar >= 2 --------- -------- false && false --------------- false Cookie Program In fact, as soon as the first false is detected, you know that the entire expression must be false, because false AND anything is false. flour >= 4 && sugar >= 2 --------- ------------ false && does not matter --------------- false As an optimization, Java only evaluates an expression as far as needed to determine the value of the entire expression. When program runs, as soon as flour >= 4 is found to be false, the entire expression is known to be false, and the false branch of the if statement is taken. This type of optimization is called short-circuit evaluation. (See the chapter on this topic.) Here is a full Java version of the cookie program. Used by permission. Page 6 of 29

Try the program with various values of flour and sugar to check that you understand how AND works. QUESTION 6: Try the program with exactly enough flour and sugar. Can you bake cookies? Used by permission. Page 7 of 29

Yes. It is always good to test programs with values that are right at the limit. Car Rental Problem A car rental agency wants a program to determine who can rent a car. The rules are: A renter must be 21 years old or older. A renter must have a credit card with $10,000 or more of credit. The program looks something like the cookie program: QUESTION 7: Complete the program by filling in the blanks. Used by permission. Page 8 of 29

if ( age>=21 && credit>=10000 ) The customer must get for both the age test and the credit test. If both tests are passed, the && combines the two 's into. More Renters A 24 year old customer with $0 credit could not rent a car. The boolean expression looks like this: age >= 21 && credit >= 10000 --------- --------------- false ---------------- false A 19 year old customer with $500000 credit could not rent a car. The boolean expression looks like this: age >= 21 && credit >= 10000 --------- --------------- false ---------------- false QUESTION 8: Could a 30 year old with $10000 credit rent a car? Used by permission. Page 9 of 29

A 30 year old with $10000 credit could rent a car. age >= 21 && credit >= 10000 --------- --------------- ---------------- Range Testing A welter weight boxer must weight between 136 and 147 pounds. A boxer's weight is tested before each fight to be sure that he is within his weight category. Here is a program that checks if a welter weight boxer's weight is within range: QUESTION 9: Fill the blank so that weight is tested in two ways: weight must be equal or greater than 136 weight must be less than or equal to 147 Used by permission. Page 10 of 29

// check that the weight is within range if ( weight >= 136 && weight <= 147 ) System.out.println("In range!" ); else System.out.println("Out of range." ); A Run of the Program The boxer must weigh enough (weight >= 136), and must also not weigh too much (weight <= 147). The results of the two tests are combined with the and-operator, &&. Here is a JavaScript version of the program: http://chortle.ccsu.edu/java5/notes/chap14/ch14_10.html QUESTION 10: Run the program for a weight of 140. Used by permission. Page 11 of 29

How heavy is the boxer? 140 In range! The and-operator gives because both sides are : weight >= 136 && weight <= 147 140 >= 136 && 140 <= 147 ------------ ----------- ----------------- Tax Bracket An unmarried taxpayer in the US with an income of $24,000 up to $58,150 (inclusive) falls into the 28% "tax bracket." Here is a program that tests if a taxpayer falls into this bracket. QUESTION 11: Fill in the blank to test if the income is within this tax bracket. Used by permission. Page 12 of 29

// check that the income is within range for the 28% bracket if ( income >=24000 && income <= 58150 ) System.out.println("In the 28% bracket." ); else System.out.println("Time for an audit!" ); Complete Boolean Expressions AND combines the results of two relational expressions, like this: income >= 24000 && income <= 58150 ------------- --------------- relational relational expression expression Each relational expression must be complete. The following is a MISTAKE: income >= 24000 && <= 58150 ------------- --------------- relational not a complete expression relational expression This is INCORRECT because the characters that follow && do not form a complete relational expression. The Java compiler would not accept this. QUESTION 12: Here is an incorrect boolean expression that is intended to test if a person's age is between 21 and 35. age >= 21 && <= 35 Fix the boolean expression. Used by permission. Page 13 of 29

age >= 21 && age <= 35 Either Order (usually) In most situations, the operands of AND can be in either order. The following age >= 21 && age <= 35 is the equivalent of this: age <= 35 && age >= 21 One false is enough to make the entire expression false, regardless of the false occurs. Warning: If a boolean expression includes an assignment operator or method calls, then the order sometimes does matter. The reason for this involves the short-circuit optimization mentioned previously. Mostly you don't need to worry about this, but make a mental note about this potential problem. Chapter 40 describes this situation in detail. For the examples in this chapter, the order of operands does not matter. QUESTION 13: Examine this expression: ( Monster.isAlive() && (hitpoints = Hero.attack()) < 50 ) Do you suspect that the order of operands in this expression matters? Used by permission. Page 14 of 29

Yes, since the expression involves calling methods and also uses an assignment operator. Buying a Car with Cash You would like to buy a $25,000 red Miata sports car. To pay for the car you need either enough cash or enough credit. Let us ignore the possibility of combining cash and credit. QUESTION 14: You found $34,951 in a cookie jar. Can you buy the $25,000 Miata? Used by permission. Page 15 of 29

Yes. You have enough money for the car. But what happened to the cookies? Recall the problem: Buying on Credit You would like to buy a new $25,000 red Miata sports car. To buy the car, you could pay cash for it, or you could buy it on credit. You might not have $25,000 on hand. The cookie jar seems to be empty. No problem you can buy on credit, if you qualify. QUESTION 15: You have $240 on hand. The credit manager is willing to extend you up to $30,000 of credit. Can you buy the $25,000 Miata? Used by permission. Page 16 of 29

Yes. You have enough credit for the car. Recall the problem: Student Car Purchase You would like to buy a new $25,000 red Miata sports car. You can pay in cash, or you can buy it on credit. It turns out that you actually have $240 on hand and are an unemployed student majoring in philosophy. The credit manager is unwilling to extend any credit to you. QUESTION 16: You have $240 on hand and no credit. Can you buy the $25,000 Miata? Used by permission. Page 17 of 29

No. Car Purchase Decision You need money OR credit. Just one would do. Of course, if you had lots of money and plenty of credit you could certainly buy the car. Sometimes a program has to test if just one of the conditions has been met. Here is how that is done with the car purchase problem: http://chortle.ccsu.edu/java5/notes/chap14/ch14_17.html The symbol (vertical-bar vertical-bar) means OR. On your keyboard, verticalbar is the top character on the key above the "enter" key. The OR operator evaluates to when either qualification is met or when both are met. The if statement asks a question with two parts: if ( cash >= 25000 credit >= 25000 ) ------------- ------------- cash part credit part If either part is, or both parts are, then the entire boolean expression is. QUESTION 17: Used by permission. Page 18 of 29

cash >= 25000 credit >= 25000 false cash >= 25000 credit >= 25000 Boolean Expressions with OR The OR operator is used in a boolean expression to check that there is at least one. If both sides are, the entire expression is. If just one side is, the entire expression is. If both sides are false, the entire expression is false. The OR operator is a logical operator because it combines two /false values into a single /false value. Here is how works: = false = false = false false = false OR checks that at least one requirement is met. This type of OR is called an inclusive OR because its value is for one or two values. Often in English word "or" is used when any number of conditions can be. For example, in this sentence Successful job seekers must have experience or training. Sometimes the English word "or" is used when only one condition can be at a time. For example, in this sentence It will rain today or it will be clear. only one condition, "rain" or "clear", can be. This is called an exclusive OR. In programming, "or" means inclusive or. Used by permission. Page 19 of 29

QUESTION 18: Here is a boolean expression: 34 > 2 5 == 7 Is this expression or false? Used by permission. Page 20 of 29

The boolean expression is 34 > 2 5 == 7 ------ ----- false -------------- because all OR needs is one. Car Purchase Program The above expression evaluates to because at least one operand was. In fact, as soon as the first is detected, you know that the entire expression must be, because OR anything is. 34 > 2 5 == 7 ------ ----- does not matter -------------- As an optimization, Java evaluates an expression only as far as needed to determine its value. When program runs, as soon as 34 > 2 is found to be, the entire expression is known to be, and evaluation goes no further. This type of optimization is called short-circuit evaluation. (Just as it is with AND.) Here is a full Java program that implements the car purchase decision. Used by permission. Page 21 of 29

Compile and run the program with various values of cash and credit to check that you understand how OR works. QUESTION 19: What does the program do if the user enters negative numbers? Used by permission. Page 22 of 29

The program runs. However, it is not clear what negative values mean in this situation. The program could be improved by calling the user's attention to possibly erroneous data. Insulated Wall Problem To meet building code requirements, outside walls of new houses must be well insulated. Say that the building code requires outside walls to be insulated with at least 4 inches of fiberglass batting or with at least 3 inches of foam insulation. Here is a program that asks for the number of inches of fiberglass and the number of inches of foam and determines if a new house meets the building code. QUESTION 20: Fill in the blanks so that the program works correctly. Used by permission. Page 23 of 29

if ( fiber >= 4 foam >= 3 ) System.out.println("House passes the code requirements!" ); else System.out.println("House fails." ); Difference between AND and OR Here is what would happen if a house had 6 inches of fiberglass batting and 0 inches of plastic foam: fiber >= 4 foam >= 3 --------- --------- false --------------- One is enough. AND is different from OR. Both of them combine Boolean values ( /false values ) into one Boolean value. But each does this in a different way: All the values AND combines must be to get a. At least one of the values OR combines must be to get a. The operation of AND and OR can be displayed in a truth table. In the table, A and B are operands. They stand for /false values or expressions that yield /false values. For example, A could stand for a relational expression such as memory > 512 or a string comparison like phrase.equals( "quit" ). Used by permission. Page 24 of 29

Each row of the truth table shows how logical operators combine the /false values of operands. For example, row one says that if A is false and B is false, then A && B is false also A B is false. Row three says that if A is and B is false, then A && B is false also A B is. All possible truth values of the operands A and B are listed in the left two columns. Each operand can take the value or the value false, so there are four possible combinations of values for the two operands. QUESTION 21: Pick or false for each of the following: (Remember that!= means "not equal.") Used by permission. Page 25 of 29

NOT! The NOT operator in Java is this:! (exclaimation point). The NOT operator changes to false and false to, as seen in the truth table. This may seem like a silly thing to do, but often it is useful. Sometimes it is more natural to express a condition in a particular way, but the program logic calls for the reverse of what you have written. Time for the NOT operator. Say that you are shopping for new shoes. You are only interested in shoes that cost less than $50. Here is a program fragment: if ( (cost < 50) ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes"); QUESTION 22: Fill in the blank so that the program fragment rejects shoes that do not cost less than $50. Used by permission. Page 26 of 29

if (!(cost < 50) ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes"); (There are other ways to write this fragment. See below.) Example It is important to put parentheses around the entire expression so the NOT is applied correctly. Say that you are considering a pair of $35 shoes. Evaluation proceeds like this:! ( cost < 50 )! ( 35 < 50 ) -----+----! ( T ) ------+-------- F The entire condition evaluates to false and so the false branch of the if statement is selected. The program prints out "Acceptable shoes". QUESTION 23: Is the following program fragment correct? if (!cost < 50 ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes"); Used by permission. Page 27 of 29

No. In this defective fragment, the NOT (the!) applies directly to cost. Precidence of NOT The NOT operator has high precedence, so it is done before arithmetic and relational operators unless you use parentheses. Examine the following:!cost < 50 ----- illegal: can't use! on an arithmetic variable Since! has high precedence, the above says to apply it to cost. This which won't work, because cost is an integer and NOT applies only to boolean values. QUESTION 24: Look at this fragment: if ( cost < 50 ) System.out.println("Acceptable shoes"); else System.out.println("Reject these shoes"); Is the new fragment equivalent to the original fragment: if (!(cost < 50) ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes"); Try a few trial costs with each fragment to see if they are equivalent. Used by permission. Page 28 of 29

Yes. The two fragments are equivalent. Often reversing the order of the branches of an if statement makes a program easier to read. End of Chapter Used by permission. Page 29 of 29