• No results found

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

N/A
N/A
Protected

Academic year: 2021

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

Copied!
29
0
0

Loading.... (view fulltext now)

Full text

(1)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 1 of 29

“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?

(2)

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?

(3)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 3 of 29

Answer:

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 true:

• 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 true 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 (true or false) does each part give you?

(4)

flour >= 4 true 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 true.

This is the role of the && (and-operator) between the two relational expressions.

The && requires that both

flour >= 4 and

sugar >= 2

are true before the entire expression is true. The entire question must be true in order for the true branch to execute.

The and operator && is a logical operator. A logical operator examines two true/false values and outputs a single true/false value.

QUESTION 4:

What is printed if the user enters 6 for flour and 4 for sugar?

(5)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 5 of 29

Answer:

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 true, because 6 >= 4 and

sugar >= 2 — is true, because 4 >= 2 Both sides are true, so AND gives true.

AND Operator

The and operator requires that both sides are true:

this side must be true && this side must be true

If both sides are true, the entire expression is true. If either side (or both) are false, the entire expression is false. && is a logical operator because it combines two true/false values into a single true/false value.

Here is what && does:

• true && true = true

• false && true = false

• true && 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?

(6)

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.

(7)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 7 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?

(8)

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.

(9)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 9 of 29

Answer:

if ( age>=21 && credit>=10000 )

The customer must get true for both the age test and the credit test. If both tests are passed, the && combines the two true's into true.

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 --- --- true 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 true

--- false

QUESTION 8:

Could a 30 year old with $10000 credit rent a car?

(10)

A 30 year old with $10000 credit could rent a car.

age >= 21 && credit >= 10000 --- --- true true

--- true

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

(11)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 11 of 29

Answer:

// 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.

(12)

How heavy is the boxer? 140 In range!

The and-operator gives true because both sides are true:

weight >= 136 && weight <= 147 140 >= 136 && 140 <= 147 --- --- true true --- true

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.

(13)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 13 of 29

Answer:

// 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.

(14)

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?

(15)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 15 of 29

Answer:

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?

(16)

Yes. You have enough money for the car. But what happened to the cookies?

Buying on Credit Recall the problem:

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?

(17)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 17 of 29

Answer:

Yes. You have enough credit for the car.

Student Car Purchase Recall the problem:

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?

(18)

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, vertical- bar is the top character on the key above the "enter" key. The OR operator evaluates to true 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 true, or both parts are true, then the entire boolean expression is true.

QUESTION 17:

     

(19)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 19 of 29

Answer:

cash >= 25000 true credit >= 25000 false

cash >= 25000 || credit >= 25000 true

Boolean Expressions with OR

The OR operator is used in a boolean expression to check that there is at least one true. If both sides are true, the entire expression is true. If just one side is true, the entire expression is true. If both sides are false, the entire expression is false. The OR operator is a logical operator because it combines two true/false values into a single true/false value.

Here is how || works:

• true || true = true

• false || true = true

• true || false = true

• 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 true for one or two true values.

Often in English word "or" is used when any number of conditions can be true.

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 true 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 true. This is called an exclusive OR.

In programming, "or" means inclusive or.

(20)

Here is a boolean expression:

34 > 2 || 5 == 7

Is this expression true or false ?

(21)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 21 of 29

Answer:

The boolean expression is true 34 > 2 || 5 == 7 --- --- true false --- true

because all OR needs is one true.

Car Purchase Program

The above expression evaluates to true because at least one operand was true.

In fact, as soon as the first true is detected, you know that the entire expression must be true, because true OR anything is true.

34 > 2 || 5 == 7 --- ---

true does not matter ---

true

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 true, the entire expression is known to be true, 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.

(22)

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?

(23)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 23 of 29

Answer:

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.

(24)

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 --- --- true false --- true

One true is enough.

AND is different from OR. Both of them combine Boolean values ( true/false values ) into one Boolean value. But each does this in a different way:

• All the values AND combines must be true to get a true.

• At least one of the values OR combines must be true to get a true.

The operation of AND and OR can be displayed in a truth table. In the table, A and B are operands. They stand for true/false values or expressions that yield true/false values. For example, A could stand for a relational expression such as memory > 512 or a string comparison like phrase.equals( "quit" ).

(25)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 25 of 29

Each row of the truth table shows how logical operators combine the true/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 true and B is false, then A && B is false also A || B is true.

All possible truth values of the operands A and B are listed in the left two columns. Each operand can take the value true or the value false, so there are four possible combinations of values for the two operands.

QUESTION 21:

Pick true or false for each of the following:

(Remember that != means "not equal.")

(26)

NOT!

The NOT operator in Java is this: ! (exclaimation point). The NOT operator changes true to false and false to true, 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.

(27)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 27 of 29

Answer:

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");

(28)

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.

(29)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

Source URL: http://chortle.ccsu.edu/java5/Notes/chap14/ch14_1.html Saylor URL: http://www.saylor.org/courses/cs101/#4.3.1

© Bradley Kjell Saylor.org

Used by permission. Page 29 of 29

Answer:

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

References

Related documents

An analysis of the economic contribution of the software industry examined the effect of software activity on the Lebanese economy by measuring it in terms of output and value

Exercise is Medicine® Australia Locked Bag 102, Albion DC QLD 4010 Phone: 07 3862 4122 | Fax: 07 3862 3588 | Email: [email protected] Role of an AEP The most

• CCAR 2011, has been followed with CCAR 2012 and CCAR 2013 – in alignment with the Dodd Frank Act’s requirements for annual capital adequacy assessment and stress

Make self-awareness, self-management and social awareness part of your relationship management toolkit.. Identify your emotional triggers Pause

En el caso de Vip Dating Perú, la evidencia física esencial está constituida por la imagen de Roxana Tutaya, así como las fotos que se exhiben de cada

This research study examined the effectiveness of the Sistas Accessing HIV/AIDS Resources At a click (SAHARA) computer-based, behavioral prevention intervention with a population

You can retain full stereo operation with two devices by connecting the left and right outputs as shown and pushing the MONO SUM switch inward on both channels.. Connected this

This paper articulates how the first phase of a design research approach was applied to explore possible solutions for designing and implementing effective online higher