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.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
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.
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.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
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.
Decision Structures and Boolean Logic
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
Decision Statements, Short- Circuit Evaluation, Errors.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
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:
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
CNG 140 C Programming (Lecture set 3)
The if…else Selection Statement
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Making Decisions.
Selections Java.
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Debugging and Random Numbers
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
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Boolean Expressions & the ‘if’ Statement
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 4: Making Decisions.
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Topics The if Statement The if-else Statement Comparing Strings
Selection CIS 40 – Introduction to Programming in Python
Outline Boolean Expressions The if Statement Comparing Data
CS139 October 11, 2004.
Logic of an if statement
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
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 4 Conditionals & Boolean Expressions Richard Gesick

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

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 End Ask for $$ Yes

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

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

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

int age = 75; bool test; test = ( age > 18 && age < 65 ); C int age = 75; bool test; test = ( age > 18 && age < 65 ); C.Wln( age + " > 18 && " + age + " < 65 is " + test ); // short circuitry with AND test = ( age < 65 && age > 18 ); C.Wln( age + " < 65 && " + age + " > 18 is " + test ); // short circuitry with OR test = ( age > 65 || age < 18 ); C.Wln( age + " > 65 || " + age + " < 18 is " + test ); // AND has higher precedence than OR test = ( age > 65 || age < 18 && false ); C.Wln( age + " > 65 || " + age + " < 18 " + " && false is " + test ); // use of parentheses to force order of execution test = ( ( age > 65 || age < 18 ) && false ); C.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 class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start < end ) { Console.WriteLine ( “A” ); } Console.WriteLine ( “B” );

“if” Example A B class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start < end ) { Console.WriteLine ( “A” ); } Console.WriteLine ( “B” ); Output A B

“if” Example class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start > end ) { Console.WriteLine ( “A” ); } Console.WriteLine ( “B” );

“if” Example B class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start > end ) { Console.WriteLine ( “A” ); } Console.WriteLine ( “B” ); 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 class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start > end ) { Console.WriteLine ( “A” ); } else { Console.WriteLine ( “B” );

“else” Example class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start > end ) { Console.WriteLine ( “A” ); } else { Console.WriteLine ( “B” ); Output B

“else” Example class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start < end ) { Console.WriteLine ( “A” ); } else { Console.WriteLine ( “B” );

“else” Example class Skeleton { public static void Main ( ) { int start = 5; int end = 19; if (start < end ) { Console.WriteLine ( “A” ); } else { Console.WriteLine ( “B” ); 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) class Skeleton { public static void Main ( ) { int start = 5; int middle = 8; int end = 19; if (start < middle ) { Console.WriteLine ( “A” ); } else if (start < end) { Console.WriteLine ( “B” );

Combining into “else if”s (Selecting one from many) class Skeleton { public static void Main ( ) { int start = 5; int middle = 8; int end = 19; if (start < middle ) { Console.WriteLine ( “A” ); } else if (start < end) { Console.WriteLine ( “B” ); Output A

else catch-all Example class Skeleton { public static void Main ( ) { int start = 5; int middle = 8; int end = 19; if (start > middle ) { Console.WriteLine ("A"); } else if (start > end) { Console.WriteLine ("B"); else { Console.WriteLine ("C");

else catch-all Example class Skeleton { public static void Main ( ) { int start = 5; int middle = 8; int end = 19; if (start > middle ) { Console.WriteLine ("A"); } else if (start > end) { Console.WriteLine ("B"); else { Console.WriteLine ("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) C.O.Wln ("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) C.Wln(“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) ) C.Wln(“HEALTHY AIR“) ;

What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) premium = 650.00 ; C.Wln(“ LOW RISK “); else premium = 1200.00 ; C.Wln(“ 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; C.Wln(“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 ;