Conditionals & Boolean Expressions

Slides:



Advertisements
Similar presentations
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Advertisements

Logic & program control part 2: Simple selection structures.
True or false A variable of type char can hold the value 301. ( F )
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
Logical Operators and Conditional statements
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Control Structures I (Selection)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Glenn Stevenson CSIS 113A MSJC CSIS 113A Lecture 2.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
C++ Programming Control Structures I (Selection).
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 5 Topics Data Type bool
CNG 140 C Programming (Lecture set 3)
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Making Decisions.
Selections Java.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Operator Precedence Operators Precedence Parentheses () unary
Boolean Expressions and If
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Boolean Expressions & the ‘if’ Statement
Topics The if Statement The if-else Statement Comparing Strings
Conditionals & Boolean Expressions
Chapter 4: Control Structures I (Selection)
Topics Data Type bool Using Relational and Logical Operators to Construct and Evaluate Logical Expressions If-Then-Else Statements If-Then Statements Nested.
CS139 October 11, 2004.
Computing Fundamentals
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Logic of an if statement
Life is Full of Alternatives
CSC 1051 – Data Structures and Algorithms I
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Conditionals and Loops
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Controlling Program Flow
Boolean Expressions & the ‘if’ Statement
CprE 185: Intro to Problem Solving (using C)
Presentation transcript:

Conditionals & Boolean Expressions Lecture 3A Conditionals & Boolean Expressions Richard Gesick Figures from Lewis, “C# Software Solutions”, Addison Wesley

Topics Flow of Control Flow Diagram bool definition Relational Operators if statements else statements

Flow of Control Sequential Method calls Selection Looping Execute instructions in order Method calls Transfer control to method, execute instructions in method, then return with or without a value Selection Execute different instructions depending on data Looping Repeat a set of instructions for different data

A Flow Diagram Start End Ask for $$ Blame it on someone else Lay low and keep hidden Did you break anything? Yes Yes No Have your parents asked about it? Yes Are you lying? No Are you passing your classes? No No Yes Ask for $$ End

The Boolean A bool is a something that resolves to true or false You can get Boolean values several different ways Simple Complex These bools will be used (later) to make decisions

Relational Operators (for primitive data types) > greater than < less than == equals != not equal >= greater than or equal <= less than or equal Notice that all of these return us a true or false value

Relational Operator Examples Literal Example 5 > 3 // true 6 != 6 // false true == (4 <= 2) // false ‘c’ != ‘b’ // true !false // true Variable Example int num1 = 5; short num2 = 7; bool result = num2 > num1; //Note: result is now true

Logical Operators ! not && and || or

&& and || Operators These operators check for multiple conditions && (AND) needs both the left and the right to be true in order to return true || (OR) needs either one (or both) to be true to return true Examples: ( (6 > 5) && ( ‘c’ == ‘b’) ) // false ( (6 > 5) && ( 7 < 9) ) // true ( (6 > 5) || ( ‘c’ == ‘b’) ) // true ( (6 > 6) || ( ‘c’ == ‘b’) ) // false

Think + and * Think of the OR (||) operator as a +, with true = 1 and false = 0. Think of the AND (&&) operator as a *, with true =1 and false =0. True || False 1 + 0 = 1 (True) False && True 0 * 1 = 0 (False)

int x, y ; x = 4; y = 6; EXPRESSION VALUE x < y x + 2 < y x int x, y ; x = 4; y = 6; EXPRESSION VALUE x < y x + 2 < y x != y x + 3 >= y y == x y == x+2 true false

EXPRESSION VALUE 7 == 7 13 < 100 -17. 32. = -17. 32 -3. 0 == 0 true false

Suppose we have three ints x, y, and z, and we want to test if x is less than both y and z. A common error is to express the condition this incorrect way: x < y && z // compiler error Each operand of a logical operator must be a boolean expression. This is correct: x < y && x < z

Short-Circuit Evaluation For any logical operator, the operands are evaluated left to right If the result of the logical operation can be determined after evaluating the first operand, the second operand is not evaluated. If the first operand of an || is true, the result will be true If the first operand of an && is false, the result will be false

Operator Precedence Precedence Operator Associativity 1 () Innermost First 2 Unary operators: + - ++ -- ! (type) Right to left 3 * / % Left to right 4 + - 5 < <= > => 6 == != 7 && 8 || 9 = += -= *= /= %= Copyright © 2012 Pearson Education, Inc.

int age = 75; bool test; test = ( age > 18 && age < 65 ); C. O int age = 75; bool test; test = ( age > 18 && age < 65 ); C.O.Wln( age + " > 18 && " + age + " < 65 is " + test ); // short circuitry with AND test = ( age < 65 && age > 18 ); C.O.Wln( age + " < 65 && " + age + " > 18 is " + test ); // short circuitry with OR test = ( age > 65 || age < 18 ); C.O.Wln( age + " > 65 || " + age + " < 18 is " + test ); // AND has higher precedence than OR test = ( age > 65 || age < 18 && false ); C.O.Wln( age + " > 65 || " + age + " < 18 " + " && false is " + test ); // use of parentheses to force order of execution test = ( ( age > 65 || age < 18 ) && false ); C.O.Wln( "( " + age + " > 65 || " + age + " < 18 ) " + "&& false is " + test );

What is the value? float x = 3.0, y = 4.0, z = 2.0; EXPRESSION VALUE 1. (x > z) && (y > z) 2. (x + y / z) <= 3.5 3. (z > x) || (z > y) 4. !(y == z) 5. (x == 1.0) || (x == 3.0) 6. (z < x) && (x < y) 7. (x <= z) || (x >= y) 8. !(x > y) || y + z >= x – z 9. !((x > y) || ((y + z) >= (x – z))) true false

Now Let’s Do Something! Using the if statement, we can decide whether or not to execute some code Has format: if (<boolean value>) { // all the code that’s in here will only execute // if and only if the boolean above is true }

“if” Example { int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } cout<< “B” <<endl;

“if” Example A B { int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } cout<< “B” <<endl; Output A B

“if” Example { s int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } cout<< “B” <<endl; s

“if” Example B { int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } cout<< “B” <<endl; Output B

The “else” statement if has a counterpart – the else statement If the if clause didn’t execute, the else clause will! Has format: if (<boolean value>) { // statements that execute if the boolean is true } else { // statements that execute if the boolean is false Notice only one set of statements executes, no matter what

“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } else cout<< “B” <<endl;

“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } else cout<< “B” <<endl; Output B

“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } else cout<< “B” <<endl;

“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } else cout<< “B” <<endl; Output A

else if’s Selecting one from many As soon as one is true, the rest are not considered Has format: if (<boolean value>) { // statements that execute if the above boolean is true } else if (<boolean value>){ else { // something that executes if nothing matched above

Combining into “else if”s (Selecting one from many) using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start < middle ) { cout<< “A” ; } else if (start < end) { cout<< “B” ;

Combining into “else if”s (Selecting one from many) using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start < middle ) { cout<< “A” ; } else if (start < end) { cout<< “B” ; Output A

else catch-all Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start > middle ) { cout<< “A” ; } else if (start > end) { cout<< “B” ; else { cout<<"C";

else catch-all Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start > middle ) { cout<< “A” ; } else if (start > end) { cout<< “B” ; else { cout<<"C"; Output C

Conclusion Boolean values can be generated several ways Use the if statement to decide which path to take Use the else to take the alternate path The else-if statements allow for selecting one from many

Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand Although it makes no difference to the compiler, proper indentation is crucial "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding

Indentation 2 Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) cout<<"Error!!"; errorCount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not

Do not put a semicolon after the condition Do not put a semicolon after the condition. Doing so indicates that the true block is empty and can cause a logic error at run time.

What went wrong? This is only supposed to display “HEALTHY AIR” if the air quality index is between 50 and 80. But when you tested it, it displayed “HEALTHY AIR” when the index was 35. int AQIndex ; AQIndex = 35 ; if (50 < AQIndex < 80) cout<<“HEALTHY AIR“ ;

Analysis of Situation AQIndex = 35; According to the precedence chart, the expression (50 < AQIndex < 80) means (50 < AQIndex) < 80 because < is Left Associative (50 < AQIndex) is false (false < 80) is ???

Corrected Version AQIndex = 35 ; int AQIndex ; AQIndex = 35 ; if ( (50 < AQIndex) && (AQIndex < 80) ) cout<<“HEALTHY AIR“ ;

What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) premium = 650.00 ; cout<<“ LOW RISK “; else premium = 1200.00 ; cout<<“ HIGH RISK ”; monthlyPayment = premium / 12.0 + 5.00; COMPILER ERROR OCCURS. The “if clause” is the single statement following the if.

Braces can only be omitted when each clause is a single statement if ( lastInitial <= ‘K’ ) volume = 1; else volume = 2; cout<<“Look it up in volume # “ << volume << “ of NYC phone book”;

If-Then-Else for a mail order Assign value .25 to discountRate and assign value 10.00 to shipCost if purchase is over 100.00 Otherwise, assign value .15 to discountRate and assign value 5.00 to shipCost Either way, calculate totalBill

These braces cannot be omitted if ( purchase > 100.00 ) { discountRate = .25 ; shipCost = 10.00 ; } else discountRate = .15 ; shipCost = 5.00 ; totalBill = purchase * (1.0 - discountRate) + shipCost ;