Boolean Logic. Boolean Expressions. What and means. And, Or, Not, True, False. What not means. What or means. Truths and Falsehoods
|
|
- Marian McCoy
- 7 years ago
- Views:
Transcription
1 Boolean Logic Boolean Expressions Truths and Falsehoods Boolean logic (algebra) is named after George Boole He wrote the book Investigation of the Laws of Thought in 1854 Also called propositional logic And, Or, Not, True, False Boolean logic is all about true and false expressions The logical connective words and, or, not In C++, type bool has two possible values: true and false bool p; bool q; What and means bool result = (p and q); p has the value true, or it has the value false q has the value true, or it has the value false result is true just if both p and q are true; otherwise result is false What or means What not means p has the value true, or it has the value false bool p; bool q; bool result = (p or q); q has the value true, or it has the value false bool p; bool result = not p; p has the value true, or it has the value false result is true just if either p or q (or both) is true; otherwise result is false result is true just if p or q is false; otherwise result is true not flips the value of a bool expression
2 Boolean Logic That's it! If you understand what's on the previous slides, you know boolean logic Let's look at some examples... All About and (true and true) is true (true and false) is false (false and true) is false (false and false) is false All About or (true or true) is true (true or false) is true (false or true) is true (false or false) is false All About not (not true) is false (not false) is true What Gets Printed? if (true) { cout << "True!"; else { cout << "False!"; True! This is an if-else statement if (true) { cout << "True!"; else { cout << "False!"; Only one of the code blocks can be executed in an if-else statement, depending on whether the condition is true or false This is the condition of the if statement; the condition is always a boolean expression When the condition is true, this code block is executed When the condition is false, this code block is executed
3 What Gets Printed? if (false) { cout << "True!"; else { cout << "False!"; False! What Gets Printed? bool all_done = true; if (all_done) { cout << "All done!"; else { cout << "More to do!"; All done! What Gets Printed? bool all_done = false; if (all_done) { cout << "All done!"; else { cout << "More to do!" More to do! What Gets Printed? bool red_cursor = true; bool blinking_cursor = false; if (red_cursor and blinking_cursor) { cout << "Red and blinking! "; cout << "Done."; Done. This statement does the same as this one: bool red_cursor(true); What Gets Printed? bool red_cursor = true; bool blinking_cursor = false; if (red_cursor and blinking_cursor) { cout << "Red and blinking! "; cout << "Done."; This statement will always be executed because it s outside the if-statement s code block This is just an if-statement, with no else part bool red_cursor = true; bool blinking_cursor = true; if (red_cursor and blinking_cursor) { cout << "Red and blinking! "; cout << "Done."; Red and blinking! Done.
4 Example Example char ch; cout << "Please enter y for yes, n for no: "; cin >> ch; if (ch == y or ch == Y ) { cout << "\nyes!"; else { cout << "\nno!"; If the user enters any other character, then No! is printed If the user enters y or Y, then Yes! is printed char ch; cout << "Please enter y for yes, n for no: "; cin >> ch; if (ch == y or ch == Y ) { cout << "\nyes!"; else { cout << "\nno!"; Note that you can put any C++ statements at all inside these code blocks, not just cout statements! Equality and Inequality == means the same as C++ let's you test if two expressions have the same or different values We use these tests all the time in boolean expressions... cout << "Please enter two numbers: "; double num1; double num2; cin << num1 << num2; if (num1 == num2) { cout << num1 << " and " << num2 << "are the same!\n"; else { cout << num1 << " and " << num2 << "are different!\n"; Be careful: don t confuse this with the assignment operator, which is =!= means different than Self-test Questions cout << "Please enter two numbers: "; double num1; double num2; cin << num1 << num2; if (num1!= num2) { cout << num1 << " and " << num2 << "are different!\n"; else { cout << num1 << " and " << num2 << "are the same!\n"; Pretend C++ didn't have!=, and show how to simulate!= using only == and not Pretend C++ didn't have ==, and show how to simulate == using only!= and not (Harder!) Pretend C++ didn't have and. Show how to simulate and using only not and or
5 == verus = name = "Mai"; if (name == "Mai") { C++ Danger: Don t Do This! if (name = "Mai") { This is an assignment. A single = means "put a copy of the value of the right-hand side into the variable on the left-hand side This is a comparison. == returns true if both name and "Mai" have the same value; otherwise, it returns false Using an assignment in an if-statement condition like this is almost always a mistake. However, C++ will let you do this! It turns out that assignments return the value being assigned (i.e. the value of the expression on the right side of =), and C++ uses some tricky conversion rules to convert the string literal "Mai" into a bool value!?! Example: Ranges In mathematics, we often write expression like this 0 < x < 1 Let's write some C++ code that prints "x is between 0 and 1" if the above is true Assume that x is a double... Example: Ranges This is legal C++, but (0 < x < 1) doesn t mean the same as the mathematical expression 0 < x < 1!! if (0 < x < 1) { // wrong!!! Example: Ranges Let s suppose x is 0, so 0 < x is false for this example... Example: Ranges We will work out this example step by step, changing the code into equivalent but simper code at each step int x = 0; // example value of x if (0 < x < 1) { // wrong!!! int x = 0; // example value of x if (0 < x < 1) { // wrong!!!
6 int x = 0; // example value of x if (0 < x < 1) { // wrong!!! Step 1: x has value 0, so we can replace x this code does the same as this code by 0 in the expression (0 < x < 1) if (0 < 0 < 1) { // wrong!!! this code does the same as this code Step 2: (0 < 0) evaluates to false, so let s replace it if (0 < 0 < 1) { // wrong!!! if (false < 1) { // wrong!!! What is false < 1? false is a bool value, and 1 is an int C++ does not let you directly compare bools to ints, but... C++ tries to be 'helpful', and in this situation automatically converts false to the int value 0 So false < 1 is the same as 0 < 1, which is true The value of false < 1 Imagine C++ 'thinking' like this: How can I calculate false < 1? I don't know how to compare bools to ints But, I do know how to compare ints to ints And, I know how to convert a bool to an int So here s what I'll do: I'll convert false to 0, and then evaluate 0 < 1 Thus, the final answer is true! if (false < 1) { // wrong!!! this code does the same as this code Step 3: in this context, false can be converted to 0 if (0 < 1) { // wrong!!! this code does the same as this code Step 4: (0 < 1) is always true if (0 < 1) { // wrong!!! if (true) { // wrong!!!
7 if (true) { // wrong!!! this code does the same as this code, and both print x is between 0 and 1 this is the original code! Step 5: compare the simplified code to the original code int x = 0; // example value of x if (0 < x < 1) { // wrong!!! Example: Ranges if (0 < x < 1) { // wrong!!! Okay, so this is wrong, but what's the right way to handle it? The right way is to split 0 < x < 1 into two parts... Example: Ranges Other Relational Operators if ((0 < x) and (x < 1)) { // correct (x < y) true just when the value of x is less than the value of y This is the correct way to test 0 < x < 1 Moral C++'s "helpfulness" sometimes causes bugs C++ can trip you up in dozens of ways Be careful out there! (x <= y) true just when the value of x is less than the value of y, or the value of x is equal to the value of y this boolean expression can be rewritten as this equivalent one: (x < y) or (x == y) Other Relational Operators A Puzzle (x > y) true just when the value of x is greater than the value of y How can you rewrite the following C++ code without using <= or <? (x >= y) true just when the value of x is less than the value of y, or the value of x is equal to the value of y this boolean expression can be rewritten as this logically equivalent one: (x > y) or (x == y) double table_friction; double box_friction; if (table_friction <= box_friction) { get rid of this!
8 A Puzzle Here's one way to figure this out: draw number lines for (a <= b), these are the two possibilities this is the one case when (a <= b) is false, and this is the key a b a b b a A Puzzle The previous number lines show that (a <= b) is true just when (a > b) is false That means (not (a > b)) is equivalent to (a <= b) Question: why does C++ provide <=, and >= if they can be rewritten in terms of other, simpler operators? Short-circuit Evaluation In C++, (p and q) is evaluated in a very particular way First p is evaluated; if p is false, then the whole expression returns false, and q is not evaluated If p is true, then q is evaluated, and its value is returned as the value of the entire expression Short-circuit Evaluation Similarly, C++ evaluates (p or q)in a very particular way First p is evaluated; if p is true, then the whole expression returns true, and q is not evaluated If p is false, then q is evaluated, and its value is returned as the value of the entire expression Short-circuit Evaluation Short-circuit evaluation can be quite useful at times, e.g. if ((n!= 0) and (200/n > 1)) { The expression (200/n > 1) is only evaluated if n is not zero Short-circuit Evaluation Often you need not worry about shortcircuit evaluation, but sometimes it makes a big difference! Sometimes, it can speed up your programs, e.g. false and (x < 1) and (y*y > 3) and (x*y*z > z*z*z) Nothing after false is evaluated!
9 Converting an int to a bool An int can also be treated as a bool 0 means false Any other int value means true This is sometimes useful, but it's wise to use bool types whenever possible C++'s parent language, C, has no bool type, so C programs rely on this int trick all the time Once upon a time, there was this guy... Fabio his name was Fabio, and he had very long hair. There was also a seagull... who had a very sharp beak. One day the seagull started flying towards Fabio... Closer... Closer and closer...
10 Closer and closer and closer! Oh yeah, Fabio was in a roller coaster, so he couldn't move. Pow!... and closer and closer, until... Pow! Right in the kisser! The seagull hit Fabio! The Seagull s Question In C++, how can you read in 3 strings from the user, and print them out in sorted order? Fabio didn't know the answer Do you? Both Fabio and the seagull got knocked over. The seagull then asked Fabio this question...
11 Screen Layout First, here's what the user will see on the screen Please enter 3 strings: fabio bonk nose Here are those strings in sorted order: bonk fabio nose High-level Pseudocode Here's the rough structure of the program read in three strings sort those strings into alphabetical order print the strings in alphabetical order Reading in strings Reading in the strings will be easy: string A; string B; string C; cout << "Please enter 3 strings: "; cin >> A >> B >> C; Once the strings are sorted, printing them out will be easy A Note on getline cin << A will not read in spaces use getline(cin,a) to read in a string that contains spaces Be careful: getline doesn t work in some versions of BC++ (e.g. the version in the assignment lab), but if you include ccc_ansi.cpp, that should fix any problems Sorting strings The < operator works with strings string name1; string name2; if (name1 < name2) { cout << name1 << " comes before " << name2 << endl; else { cout << name2 << " comes before " << name1 << endl; Lexicographic Ordering C++ strings can consist of any sequence of characters, including numbers, punctuation, spaces, upper case and lower case letters, The < operator puts all strings into lexicographic order according to the ASCII (or ANSI) code every character has a unique integer code
12 Lexicographic Ordering Read the details of how lexicographic ordering work (p ) All the basic relational operators work with strings: ==,!=, <, <=, >, >= What we need to know is that if (str1 < str2) is true, then str1 comes before str2 Sorting Two Strings string A; string B; cin >> A >> B; if (A > B) { // swap A and B string temp = A; A = B; B = temp; cout << A << B; Sorting Three Strings Arranging 3 Strings There are a number of different ways to do this using if statements I'll do it using brute force: an if-else-if statement that considers all possible orderings You should find a shorter way to do this There are only 6 ways that the 3 strings A, B, and C can be arranged Write an if-else-if statement that recognizes each of these cases, and rearranges A, B, C Case 1: A <= B <= C Case 2: A <= C <= B Case 3: B <= A <= C Case 4: B <= C <= A Case 5: C <= A <= B Case 6: C <= B <= A if ((a <= b) and (b <= c)) { // case 1 // nothing do, already sorted else if ((a <= c) and (c <= b)) { // case 2 // swap c and b else if ((b <= a) and (a <= c)) { // case 3 // swap a and b else if ((b <= c) and (c <= a)) { // case 4 // swap a and b, then swap b and c else if ((c <= a) and (a <= b)) { // case 5 // swap a and b, then swap c and a else if ((c <= b) and (c <= a)) { // case 6 // swap a and c Filling in the Details The previous if-else-if statement shows exactly how to continue You just need to write the code to do the required swaps you already know how to swap variables! The way this program has been developed is a good example of topdown design
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationChapter 8 Selection 8-1
Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationif and if-else: Part 1
if and if-else: Part 1 Objectives Write if statements (including blocks) Write if-else statements (including blocks) Write nested if-else statements We will now talk about writing statements that make
More informationChapter 5. Selection 5-1
Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationWhat is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...
What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control
More informationIntroduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:
More informationExample. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:
Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,
More informationThe C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures
The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops
More informationLecture 2 Notes: Flow of Control
6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The
More informationLogic in Computer Science: Logic Gates
Logic in Computer Science: Logic Gates Lila Kari The University of Western Ontario Logic in Computer Science: Logic Gates CS2209, Applied Logic for Computer Science 1 / 49 Logic and bit operations Computers
More informationBoolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
More informationOutline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions
More informationThe While Loop. Objectives. Textbook. WHILE Loops
Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE
More informationPassing 1D arrays to functions.
Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,
More informationBasics of I/O Streams and File I/O
Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading
More informationRegular Expressions and Automata using Haskell
Regular Expressions and Automata using Haskell Simon Thompson Computing Laboratory University of Kent at Canterbury January 2000 Contents 1 Introduction 2 2 Regular Expressions 2 3 Matching regular expressions
More informationLecture Notes on Linear Search
Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is
More informationArrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays
Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from
More informationCS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
More information9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements
9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending
More informationMember Functions of the istream Class
Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,
More informationCommon Beginner C++ Programming Mistakes
Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't
More informationConditions & Boolean Expressions
Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In
More informationPIC 10A. Lecture 7: Graphics II and intro to the if statement
PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the
More informationSequential Program Execution
Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.
More information3. Mathematical Induction
3. MATHEMATICAL INDUCTION 83 3. Mathematical Induction 3.1. First Principle of Mathematical Induction. Let P (n) be a predicate with domain of discourse (over) the natural numbers N = {0, 1,,...}. If (1)
More informationBinary Adders: Half Adders and Full Adders
Binary Adders: Half Adders and Full Adders In this set of slides, we present the two basic types of adders: 1. Half adders, and 2. Full adders. Each type of adder functions to add two binary bits. In order
More informationOperator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example
Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics
More informationAnswers to Review Questions Chapter 7
Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element
More informationBoolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.
Boolean Expressions Boolean Expressions Sometimes a programmer would like one statement, or group of statements to execute only if certain conditions are true. There may be a different statement, or group
More informationCommon Data Structures
Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees
More information6. Control Structures
- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,
More informationLinear Programming Notes V Problem Transformations
Linear Programming Notes V Problem Transformations 1 Introduction Any linear programming problem can be rewritten in either of two standard forms. In the first form, the objective is to maximize, the material
More information13 Classes & Objects with Constructors/Destructors
13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.
More informationC++ Input/Output: Streams
C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream
More informationPlaying with Numbers
PLAYING WITH NUMBERS 249 Playing with Numbers CHAPTER 16 16.1 Introduction You have studied various types of numbers such as natural numbers, whole numbers, integers and rational numbers. You have also
More informationBoolean Algebra Part 1
Boolean Algebra Part 1 Page 1 Boolean Algebra Objectives Understand Basic Boolean Algebra Relate Boolean Algebra to Logic Networks Prove Laws using Truth Tables Understand and Use First Basic Theorems
More informationMS Visual C++ Introduction. Quick Introduction. A1 Visual C++
MS Visual C++ Introduction 1 Quick Introduction The following pages provide a quick tutorial on using Microsoft Visual C++ 6.0 to produce a small project. There should be no major differences if you are
More informationMethod To Solve Linear, Polynomial, or Absolute Value Inequalities:
Solving Inequalities An inequality is the result of replacing the = sign in an equation with ,, or. For example, 3x 2 < 7 is a linear inequality. We call it linear because if the < were replaced with
More informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationNumeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:
Numeral Systems Which number is larger? 25 8 We need to distinguish between numbers and the symbols that represent them, called numerals. The number 25 is larger than 8, but the numeral 8 above is larger
More informationCalling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?
Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function
More informationUIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything
More informationWe will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
More information26 Integers: Multiplication, Division, and Order
26 Integers: Multiplication, Division, and Order Integer multiplication and division are extensions of whole number multiplication and division. In multiplying and dividing integers, the one new issue
More informationSolving Problems Recursively
Solving Problems Recursively Recursion is an indispensable tool in a programmer s toolkit Allows many complex problems to be solved simply Elegance and understanding in code often leads to better programs:
More informationPreliminary Mathematics
Preliminary Mathematics The purpose of this document is to provide you with a refresher over some topics that will be essential for what we do in this class. We will begin with fractions, decimals, and
More informationObject Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationCompiler I: Syntax Analysis Human Thought
Course map Compiler I: Syntax Analysis Human Thought Abstract design Chapters 9, 12 H.L. Language & Operating Sys. Compiler Chapters 10-11 Virtual Machine Software hierarchy Translator Chapters 7-8 Assembly
More informationAppendix K Introduction to Microsoft Visual C++ 6.0
Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):
More informationC++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore
More informationMoving from C++ to VBA
Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry
More informationSession 7 Fractions and Decimals
Key Terms in This Session Session 7 Fractions and Decimals Previously Introduced prime number rational numbers New in This Session period repeating decimal terminating decimal Introduction In this session,
More informationCSC 221: Computer Programming I. Fall 2011
CSC 221: Computer Programming I Fall 2011 Python control statements operator precedence importing modules random, math conditional execution: if, if-else, if-elif-else counter-driven repetition: for conditional
More informationThe if Statement and Practice Problems
The if Statement and Practice Problems The Simple if Statement Use To specify the conditions under which a statement or group of statements should be executed. Form if (boolean-expression) statement; where
More informationPseudo code Tutorial and Exercises Teacher s Version
Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy
More informationPart 1 Expressions, Equations, and Inequalities: Simplifying and Solving
Section 7 Algebraic Manipulations and Solving Part 1 Expressions, Equations, and Inequalities: Simplifying and Solving Before launching into the mathematics, let s take a moment to talk about the words
More informationIS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction
IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points
More information3.2. Solving quadratic equations. Introduction. Prerequisites. Learning Outcomes. Learning Style
Solving quadratic equations 3.2 Introduction A quadratic equation is one which can be written in the form ax 2 + bx + c = 0 where a, b and c are numbers and x is the unknown whose value(s) we wish to find.
More informationCosmological Arguments for the Existence of God S. Clarke
Cosmological Arguments for the Existence of God S. Clarke [Modified Fall 2009] 1. Large class of arguments. Sometimes they get very complex, as in Clarke s argument, but the basic idea is simple. Lets
More informationSample CSE8A midterm Multiple Choice (circle one)
Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names
More informationQUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1
QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For
More information6. Standard Algorithms
6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary
More informationCHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.
CHAPTER 2 Logic 1. Logic Definitions 1.1. Propositions. Definition 1.1.1. A proposition is a declarative sentence that is either true (denoted either T or 1) or false (denoted either F or 0). Notation:
More informationWhile Loop. 6. Iteration
While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true
More information3.3 Addition and Subtraction of Rational Numbers
3.3 Addition and Subtraction of Rational Numbers In this section we consider addition and subtraction of both fractions and decimals. We start with addition and subtraction of fractions with the same denominator.
More information1. The Fly In The Ointment
Arithmetic Revisited Lesson 5: Decimal Fractions or Place Value Extended Part 5: Dividing Decimal Fractions, Part 2. The Fly In The Ointment The meaning of, say, ƒ 2 doesn't depend on whether we represent
More informationFibonacci Numbers and Greatest Common Divisors. The Finonacci numbers are the numbers in the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,...
Fibonacci Numbers and Greatest Common Divisors The Finonacci numbers are the numbers in the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,.... After starting with two 1s, we get each Fibonacci number
More informationWRITING PROOFS. Christopher Heil Georgia Institute of Technology
WRITING PROOFS Christopher Heil Georgia Institute of Technology A theorem is just a statement of fact A proof of the theorem is a logical explanation of why the theorem is true Many theorems have this
More informationInformatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)
More informationConditional Statements. 15-110 Summer 2010 Margaret Reid-Miller
Conditional Statements 15-110 Summer 2010 Margaret Reid-Miller Conditional statements Within a method, we can alter the flow of control (the order in which statements are executed) using either conditionals
More informationComp151. Definitions & Declarations
Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const
More informationPROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON
PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London
More informationMathematical Induction
Mathematical Induction (Handout March 8, 01) The Principle of Mathematical Induction provides a means to prove infinitely many statements all at once The principle is logical rather than strictly mathematical,
More informationASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters
The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters
More informationPython Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e 1 Objectives æ To understand the concept of Boolean expressions and the bool data
More informationRecursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD
1 Slides 1. Table of Contents 2. Definitions 3. Simple 4. Recursive Execution Trace 5. Attributes 6. Recursive Array Summation 7. Recursive Array Summation Trace 8. Coding Recursively 9. Recursive Design
More informationBoolean Logic in MATLAB
Boolean Logic in MATLAB When programming, there will be times when you want to control the flow of your code based on certain events occurring or certain values being reached. Primarily, this is handled
More informationMathematical Induction
Mathematical Induction In logic, we often want to prove that every member of an infinite set has some feature. E.g., we would like to show: N 1 : is a number 1 : has the feature Φ ( x)(n 1 x! 1 x) How
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-3: Boolean Logic and Assertions reading: 5.3 5.5 1 2 Type boolean boolean: A logical type whose values are true and false. A logical test is actually a boolean
More informationThe design recipe. Programs as communication. Some goals for software design. Readings: HtDP, sections 1-5
The design recipe Readings: HtDP, sections 1-5 (ordering of topics is different in lectures, different examples will be used) Survival and Style Guides CS 135 Winter 2016 02: The design recipe 1 Programs
More informationPython Evaluation Rules
Python Evaluation Rules UW CSE 160 http://tinyurl.com/dataprogramming Michael Ernst and Isaac Reynolds mernst@cs.washington.edu August 2, 2016 Contents 1 Introduction 2 1.1 The Structure of a Python Program................................
More informationCS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A
More informationVariables, Constants, and Data Types
Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight
More informationCOMPUTER SCIENCE 1999 (Delhi Board)
COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?
More informationTopic 16 boolean logic
Topic 16 boolean logic "No matter how correct a mathematical theorem may appear to be, one ought never to be satisfied that there was not something imperfect about it until it also gives the impression
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
More informationThe Peruvian coin flip Cryptographic protocols
Activity 17 The Peruvian coin flip Cryptographic protocols Age group Older elementary and up. Abilities assumed Requires counting, and recognition of odd and even numbers. Some understanding of the concepts
More informationChapter 4: Computer Codes
Slide 1/30 Learning Objectives In this chapter you will learn about: Computer data Computer codes: representation of data in binary Most commonly used computer codes Collating sequence 36 Slide 2/30 Data
More informationJ a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
More informationUEE1302 (1102) F10 Introduction to Computers and Programming
Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming Programming Lecture 03 Flow of Control (Part II): Repetition while,for & do..while Learning
More informationA binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:
Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)
More informationThinking of a (block) cipher as a permutation (depending on the key) on strings of a certain size, we would not want such a permutation to have many
Fixed points of permutations Let f : S S be a permutation of a set S. An element s S is a fixed point of f if f(s) = s. That is, the fixed points of a permutation are the points not moved by the permutation.
More informationClasses and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:
In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our
More informationSelection Statements
Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:
More informationComputer Organization
Basics Machine, software, and program design JPC and JWD 2002 McGraw-Hill, Inc. Computer Organization CPU - central processing unit Where decisions are made, computations are performed, and input/output
More informationTopic 11 Scanner object, conditional execution
Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright
More information