Unit 2: Boolean Algebra

advertisement

AP Computer Science

Mr. Haytock

Unit 2: Boolean Logic

Topics :

I.

Syllogisms and propositional logic

II.

Logical operators

III.

Constructing truth tables

IV.

Laws of Boolean algebra

V.

Boolean operations in programming languages

VI.

Bitwise logical operations

Materials :

I.

Pohl and Shaw ch. IV

II.

Boolean exercises #1

III.

Boolean exercises #2

IV.

Boolean exercises #3

V.

Challenge Questions

VI.

Bitwise operations program

VII.

Full adder specifications

VIII.

Sample code

IX.

Review sheet

X.

Sample Free Response question

1

2

3

4

5

6

7

8

9

10

11

12

13

Boolean Exercises #1

I. The following are compound statements. Find their simple components, and assign a symbol to each. Write them in symbolic form. a. It is hot and it is raining. b. Jack and Jill went up the hill. c. If it is raining or snowing, we will cancel the picnic.

II. Let P be “Fred is smart” and Q be “George is smart.” Write the following statements in symbolic form. a. Fred is smart and George is stupid. b. Fred and George are both stupid. c. Either Fred is smart or George is stupid. d. It is not true that Fred and George are both stupid.

III. Assume that Fred and George are both smart. Which of the above compound statements would be true?

14

IV. Let P be “Stock prices are high” and Q be “Stocks are rising.” Give a verbal translation for each of the following. a. P

~Q b. ~P

~Q c. ~(P

Q) d. ~(~P

~Q)

V. Construct a truth table for the following: (P

Q)

(Q

P)

VI. Let P be “It is raining” and Q be “It is windy.” Translate the following into symbolic form and give a truth table for each: a. If the wind blows then it does not rain. b. The wind blows if and only if it rains.

15

Boolean Exercises #2

I. Translate the following sentences into symbolic propositional logic expressions. First, assign a symbol for each primary component, then put it together with the proper symbols. a. The cat is either male or female, but not both. b. Either John is not speaking and Mary is speaking or John is speaking and Mary

is speaking.

II. Use truth tables to prove that: a) A

(B

A) is a tautology b)

(A ∩ B) ≡ 

A

 

B c) A

B

 

B

 

A d) (A

 

B)

(A

B) is a contradiction. e) A ∩ (B

C) ≡ (A ∩ B)

(A ∩ C) f) A ∩ (A

B) is the same as A

16

Boolean Exercises #3

1. The Boolean expression ((isDone || input==’a’) && input==’a’) is equivalent to which of the following expressions? a) i sDone b) i nput==’a’ c) isDone || input==’a’ d) isDone && input==’a’ e) 1 (it is always true)

2. The Boolean expression ( (degrees < 32 && degrees > 0) && degrees < 32) is equivalent to which of the following expressions? a) degrees < 32 b) degrees > 0 c) degrees < 32 || degrees > 0 d) degrees < 32 && degrees > 0 e) 1 (it is always true)

3) The Boolean expression ( !(numFiles/4 > 0 || inChar > 65)) is equivalent to which of the following expressions? a) numFiles/4 > 0 != inChar > 65 b) !(numFiles/4 > 0) || inChar > 65 c) numFiles/4 > 0 && inChar > 65 d) !(numFiles/4 > 0) || !(inChar > 65) e) !(numFiles/4 > 0) && !(inChar > 65)

4) The Boolean expression ( !((numStudents < numFaculty) && (numStaff > numCoaches))) is equivalent to which of the following expressions? a) ( numStudents < numFaculty) || (numStaff > numCoaches) b) (numStudents >= numFaculty) && (numStaff <= numCoaches) c) (numStudents >= numFaculty)||( numStaff <= numCoaches) d) (numStudents > numFaculty) && (numStaff < numCoaches) e) (numStudents > numFaculty) || (numStaff < numCoaches)

17

5) What is the effect of the following short Java code fragment?

String command = “A”; do

{

System.out.println(command);

command = Keyboard.readString();

} while (!command.equals(“q”) || !command.equals(“Q”)); a.

The loop will terminate if the string “q” is entered or if the string “Q” is entered. b.

The loop will terminate only if the string “q” is entered. c.

The loop will terminate only if the string “Q” is entered. d.

The loop will never terminate—an infinite loop will result. e.

The loop will terminate after its first iteration no matter what is entered.

6. Given the Boolean variables “P” and “Q” what is an equivalent statement to the following? if ( (P && !Q) || (!P && Q) ) a. if (true) b. if (false) c. if (P || Q) d. if (P ^ Q) e. if (P && Q)

7. In Java, what is the result of the following: 11 | 12 a. true b. false c. 3 d. 7 e. 15

8. In Java, what is the result of the following: 11 ^ 12 a. true b. false c. 3 d. 7 e. 15

18

Boolean Algebra Challenge Problems

1. Simplify:

(

 

A

2. Simplify:

) (

3. The two arguments in the expression below are hexadecimal representations of bit strings that are 12-bits long. Evaluate the expression and express your answer as a 3-digit hexadecimal string.

A26 XOR 7B5

4. List all the values of X (a 5-bit string) that make the expression TRUE.

((LCIRC-3 (X AND 10010)) OR (RSHIFT-2 (X AND 01101)) = 10011

5. How many ordered triples make the following circuit TRUE?

A

B

C

19

AP Computer Science

Mr. Haytock

Programming Assignment No. 1:

Bitwise Command Interpreter

Specifications: As we have been discussing in class, at the hardware level, a computer is constantly performing calculations by turning bits on and off. One of the ways that the computer organizes these switches into a recognizable calculation is to control the flow of electricity by means of gates to perform Boolean logic. We have seen this on the board, but as the old Chinese proverb says: “I hear and I forget; I see and I remember; I do and I understand.”

Write a program that interprets a list of bitwise Boolean operations and performs them on the data given. Your program should evaluate bitwise and, or, exclusive or, not, left shift, and right shift.

Input : Your input will come from a file specified by the user (read the file name at run-time).

The file will contain an indeterminate number of lines. The program will quit when it reaches a blank line or a sentinel value (e.g. ‘q’ to quit). Each line will contain a command following by one or two decimal numbers separated by a single space. A few sample input lines could be as follows:

& 12 10

| 12 20

& 15 7

^ 15 19

> 44 2 q

Your output will go to a file called “bitwiseops.out.” For the input file given above, the output file would be:

12 AND 10 ==> 8

12 OR 20 ==> 28

15 AND 7 ==> 7

15 XOR 19 ==> 28

44 SHR by 2 bits ==> 11 quitting

Submission Format : Hand in to me a printout of your source code files, a printout of your input and output files, and concluding reflections. Also turn in an electronic copy of these files. The project is due: __________, __________. I’ll accept it up until 3 PM before I count it late. Be sure to document your work well with appropriate and useful comments!

II. Design Phase

Before implementing, consider everything that needs to be accomplished in this program. A framework of the adder class will be given to you. For the time being, consider these questions:

Where is our input coming from? What form is it in? What data types can we use to

20

hold the information?

What inputs will each method need, and what should they output? Any pre-conditions and post-conditions?

III. Implementation

Use the built-in bitwise operators for this project.

&: an

|: or

^: exclusive or

~: complement (bit-wise not)

>>: shift right

<<: shift left

IV.Testing: I suggest that you choose input which will effectively test your program test your program and determine whether or not the results of each operation are what you expected.

When you are finished, write a short (perhaps half a page) summary of which commands did / did not do what you expected. Can you explain the results of the shifting commands? Can you explain the results of the complement (not) operation? What kinds of common exceptions should be handled? Be sure that you document how your program handles all possible cases.

21

/* NAME:

DATE:

Description: Bitwise operator testing template. */ import cs.ssa.*; // imports the file I/O classes import cs1.Keyboard; // for keyboard I/O class BitwiseOperatorTester

{

static InFile inFile;

static OutFile outFile; static public void main(String[] args)

{ char command = ""; prepIO(); do

{

} command = inFile.read(); inFile.read(); // skip blank processCommand(command); while (command != ‘q’);

}

}

static public void prepIO()

// prepares the input and output streams

{

String fileName;

System.out.println("Please enter file name: "); fileName = Keyboard.readString(); inFile = new InFile(fileName); outFile = new OutFile(“bitwiseops.out”); static public void processCommand(char command)

// Uses only the first character of the command

{

}

} switch (command)

{

case '&': do_And(); break;

case '|': do_Or(); break;

case '^': do_XOR(); break;

case '~': do_Not(); break;

case '>': do_ShR(); break;

case '<': do_ShL(); break; static private void do_And()

{

/* your code should output a line according to the specifications */

}

}

22

AP Computer Science

Mr. Haytock

Programming Assignment No. 1:

The Full Adder

Specifications: As we have been discussing in class, at the hardware level, a computer is constantly performing calculations by turning bits on and off. One of the ways that the computer organizes these switches into a recognizable calculation is to control the flow of electricity by means of gates to perform Boolean logic. We have seen this on the board, but as the old Chinese proverb says: “I hear and I forget; I see and I remember; I do and I understand.” On a very basic level, we’re going to build a machine that can add. Our program will input a list of pairs of bytes in binary form. It will add each pair of numbers and get the result. To simulate hardware gates, we will restrict our program to accomplishing this only by means of bitwise operations.

I/O option 1 : Your input may come from a file specified by the user (read the file name at runtime). The file will contain an indeterminate number of lines. The program will quit when it reaches a blank line or a sentinel value (e.g. ‘q’ to quit). Each line will contain two binary numbers separated by a single space. A few sample input lines could be as follows:

00001100 00000011

00000011 00000010

00000011 00000001

10010011 10001110

Your output will go to a file called adder.out

. This file will contain the results of adding the numbers from the input file. For the input file given above, the output file would be:

Num1: 00001100 Num2: 00000011 Result: 00001111

Num1: 00000011 Num2: 00000010 Result: 00000101

Num1: 00000011 Num2: 00000001 Result: 00000100

Num1: 10010011 Num2: 10001110 Result: 00100001

I/O option 2: Create a GUI (graphical user interface).

A list of eight images are to be drawn across the screen in a regular pattern for each number. The images “1.gif” and “0.gif” are available to you—each one is 50 x 50 pixels. Add a mouse listener that determines whether or not a number has been clicked.

A given number should switch between 0 and 1 when clicked. Finally, add a “go” button that will perform the arithmetic.

Hand in to me a printout of your source code files, a printout of your input and output files or screen shots with test data, and concluding reflections. Also turn in an electronic copy of these files. The project is due: __________, __________. I’ll accept it up until 3 PM before I count it late. Be sure to document your work well with appropriate and useful comments!

23

II. Design Phase

Before implementing, consider everything that needs to be accomplished in this program. A framework of the adder class will be given to you. For the time being, consider these questions:

Where is our input coming from? What form is it in? What data types can we use to hold the information?

What algorithm needs to be done to perform the addition? Remember, that we are using bit-wise operations on a series of binary digits.

What inputs will each method need, and what should they output? Any pre-conditions and post-conditions?

If using a GUI, how should the screen be partitioned? Diagram it.

III. Implementation

An “adding machine” class is required for this project. You are required to store your two input numbers as arrays of type “boolean” (convert strings to boolean arrays). From there, the addition feature should be accomplished by means of Boolean tests.

If you are using a GUI, you will need to refer to the GraphicsWindow class features. Two of the important ones you will need include the “drawImage” command, requiring a file name and an

(x,y) pair for parameters. The second is the “mousePressed” method, overridden from the parent class, which requires an (x,y) pair of parameters. See the sample code for a framework.

IV.Testing

I suggest that you choose input which will effectively test your program—this means perhaps trying a data with numbers that are simple, numbers that are complicated, and numbers that create “overflow.” What kinds of data combinations do you need to test in order to know whether your program works correctly? What kinds of common exceptions should be handled?

Be sure that you document how your program handles all possible cases.

24

/* Name:

Date:

Description: Framework for the FullAdder class to be filled in by student */ public class FullAdder

{ private boolean inputA; private boolean inputB; private boolean inputCarry; private boolean result; private boolean outputCarry; public FullAdder()

// default constructor--initialize to default values

{

}

/* Modifier / mutator methods */ public void setA(boolean newA)

{ } public void setA(int newA)

{ }

// alternative input ??

// add methods for setting circuitB and the input carry

/* Accessor methods */ public boolean getA()

{ return inputA;

}

}

// add methods for getting other values public void add()

/* Perform the addition logic */

{

} public String toString()

/* Useful for showing data in text form. */

{

} return "";

25

{

/* Name:

Date:

Description: Framework for AdderDriver */ import cs.ssa.*; class AdderDriver2010

{ static public void main(String[] args)

{

BitWindow myWindow = new BitWindow(600, 500);

}

} class BitWindow extends SSAWindow private final int XLEFT = 50; // set screen constants private final int ROW1YTOP = 50; private final int IMAGESIZE = 50; private final int MAXBITS = 8; private boolean[] num1; private boolean[] num2; private boolean[] num3; public BitWindow(int width, int height) // initialize window and values

{

} super(width, height); num1 = new boolean[MAXBITS]; num2 = new boolean[MAXBITS]; num3 = new boolean[MAXBITS]; drawScreen();

// arrays of booleans represent the numbers

} private void drawScreen()

/* Draws the icons representing the trues and falses stored in our three arrays of booleans. */

{

// erase previous screen

// draw an image for the button to perform the addition

// use a loop to draw icons for the input and output numbers public void add()

/* Use a "FullAdder" object (or several of them to perform the addition. */

{

} public void mousePressed(int xP, int yP)

/* The header for "mousePressed" must be written exactly as it is. This is an overridden method from the parent "GraphicsWindow" class. */

{

System.out.println("X: " + xP + " Y: " + yP); if (goClicked(xP, yP))

{ add();

// for testing purposes

26

}

}

} else

{ lookForButton(xP, yP);

} drawScreen(); // re-draw the screen in case things have changed public boolean goClicked(int x, int y)

/* Test to see if the mouse coordinates overlap the "go" button area. */

{ return (x > XLEFT+IMAGESIZE*9 && x < XLEFT+IMAGESIZE*10 && y > ROW1YTOP + IMAGESIZE*3 && y < ROW1YTOP + IMAGESIZE*4);

} public void lookForButton(int x, int y)

/* Try to determine if the mouse coordinates overlap the area of any of the input bit areas. First find the row, then the column. */

{

int row;

int column;

row = (y - ROW1YTOP) / IMAGESIZE; // row may be 0, 1 or out of bounds

column = (x - XLEFT) / IMAGESIZE; // column may be 0 .. 7 or out of bounds

if (row == 0)

{

// look for bit in num1

if (column>= 0 && column < 8)

{

} num1[column] = ! num1[column]; // flip value between true / false

}

else if (row == 1) // look for bit in num2

{

if (column>= 0 && column < 8)

{ num2[column] = ! num2[column]; // flip value between true and false

}

}

}

27

AP Computer Science

Mr. Haytock

Review for Test #1:

Boolean Logic

I. Review Exercises:

A. Symbolic Notation : Be sure that you understand how to find the elementary propositions in an English sentence and how to put them together to make a symbolic expression. Translate the following English sentences into symbolic form: a. John and Mary are both speaking or John and Mary are not both speaking. b. John and Mary are not both speaking if and only if John is not speaking or Mary is not

speaking.

B. Truth Tables : Be sure that you can set up truth tables and use them to show the possible values for given expressions. You should also be able to use truth tables to show certain tautologies and contradictions . Set up a truth table for each of the following: a. Q

~Q

P b. P

~ Q

R

C. Boolean Algebra : Understand and be able to apply the major laws of Boolean Algebra. For practice, choose two of them and draw up a truth table for them. a. b.

28

D. Boolean Logic in Programming : Evaluate each of the Java expressions below, given the following information: thereAreErrors = true total = 88 earned = 65 a.

!thereAreErrors || total <= earned b.

thereAreErrors && !(total <= earned || (total - earned) > 0) c.

thereAreErrors == ((total / earned) > 0) d. (!thereAreErrors && total == 88)

E. Terms : Provide definitions for the following terms: a. Tautology b. Contradiction c. Short-circuit evaluation d. Precedence of operators e. Syllogistic argument

F. Combinational Logic Circuits : Be able to recognize the symbols for AND gates, OR gates, etc. and how to put them together for truth values. Understand Bitwise operations. a. Draw a symbolic circuit diagram for the expression: c = ~(a & (b | !a)) b. What are the results of the following bit-wise operations?

1.

7 & 8

2.

10 & 21

3.

7 | 8

4.

10 | 21

5.

12 ^ 14

II.

Programming : review the full adder program. Be sure that you understand the project specifications, design, and implementation.

III.

Lecture Material

: Anything I’ve said in class is fair game.

IV.

Reading Material : Review excerpts from Pohl and Shaw on Boolean Algebra.

29

AP Computer Science

Practice Free Response

Boolean #3

Solve the problem below. Write your solution using clear, correct Java code.

Circuitry Coding : Write a method that correctly simulates the integrated circuit that is described by the gate diagram below. You are to write the method header, naming the method

“circuitDiagram.” It should return a Boolean value and receive three Boolean type parameters

(you may name them ‘A’, ‘B’, and ‘C’). You do not have to simplify the expression, although you can if you wish.

A

B

C

An example of how this method is to be called might as follows: if (circuitDiagram(true, true, false))

{

beginMethod()

30

31

Download