Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.

Slides:



Advertisements
Similar presentations
Selection in Python If statements.
Advertisements

CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Logic & program control part 2: Simple selection structures.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 9/24/07CS150 Introduction to Computer Science 1 Relational Operators and the If Statement.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Flow of Control is Sequential unless a “control structure” is used to change that there are 2 general types of control structures: Selection (also called.
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Conditions, logical expressions, and selection Introduction to control structures.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
1 Chapter 4 Selection and Encapsulation. 2 Chapter 4 Topics l Java Control Structures l boolean Data Type l Using Relational and Logical Operators in.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Control Structures I (Selection)
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Conditions, Logical Expressions, and Selection Control Structures Sumber dari :
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions, logical expressions, and selection Introduction to control structures.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Flow of Control There are 5 general types of Java control structures: Sequence (by default) Selection (also called branch or decision) Loop (also called.
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Lecture no 3 Control statements.
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
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.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
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.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions, Logical Expressions, and Selection Control Structures.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
C++ Programming Control Structures I (Selection).
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter 5 Topics Data Type bool
The Ohio State University
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Programming Fundamentals
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Topics Data Type bool Using Relational and Logical Operators to Construct and Evaluate Logical Expressions If-Then-Else Statements If-Then Statements Nested.
Chapter 7 Conditional Statements
Chapter 4: Control Structures I (Selection)
Presentation transcript:

Selection in C++ If statements

Control Structures Sequence Selection Repetition Module

Selection If or if / else statement choosing between mutually exclusive possibilities Two forms  if (logical expression) statement; else statement;

Logical Expressions Relational Operators ==, !=, =, >, < They are binary operators – have two operands work on any type of data, be careful about matching types watch out for = and == produce a bool result

Syntax of if statement if (logical expression) statement; Don't put semicolon after condition Indentation helps humans, doesn't matter to compiler

Syntax of if statement if (x > 0) y = sqrt(x); if (x > y) t = x; x = y; y = t; // what goes with the if?

If-Then Statement Determine whether or not to execute a statement (which can be a single statement or an entire block) TRUE FALSE statement expression

Examples output larger of two numbers don't allow sqrt of negative number don't allow overflow determining even or odd give student another chance at a question

Visual Aid Decision tree  “if person is 18 or over and state is KY, they can have regular license”  “if person is 16 or over and under 18 and state is TN or VA, they can have learner’s permit”  “if person is under 16, in any state, they can’t have license”  “if person is over 65 in VA, they have modified license”

Example What is output? Why? int age; age = 20; if (age = 16) { cout << “Did you get driver’s license?”; }

Example What is output? Why? int age; age = 30; if (age < 18) cout << “Do you drive?”; cout << “Too young to vote”;

Example What is output? Why? int number; number = 0; if (number = 0) cout << “Zero value”; else cout << “Non-zero value”;

Logical Operators And (&&) Or (||) Not (!) && and || are binary operators, ! is unary used to combine bool values produce a bool result truth tables operator precedence  ! then && then ||  ! is very high, above most operators  && and || are very low, below other operators

OperatorMeaning Associativity ! NOTRight *, /, % Multiplication, Division, Modulus Left +, - Addition, SubtractionLeft < Less thanLeft <= Less than or equal toLeft > Greater thanLeft >= Greater than or equal toLeft == Is equal toLeft != Is not equal to Left && ANDLeft || OR Left = AssignmentRight 14

Logical Expression MeaningDescription ! p NOT p ! p is false if p is true ! p is true if p is false p && q p AND q p && q is true if both p and q are true. It is false otherwise. p || q p OR qp || q is true if either p or q or both are true. It is false otherwise.

Converting English to logic "0 is less than x is less than 5" "x is 5 or 6" "x is bigger than 5 and less than 10" impossible situations "dead code"  always true – “x 5 || x < 8”  always false – “x 10”

Write an expression for each taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22

Some Answers (taxRate >.25) && (income < 20000) (temperature <= 75) || (humidity <.70) (age > 21) && (age < 60) (age == 21) || (age == 22)

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 (has value 0) (0 < 80) is true.

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

Nested if's the statement to be executed in an if statement can be another if an else branch goes with the nearest if "dangling else"

Example float average; average = 100.0; if (average >= 60.0) if (average < 70.0) cout << “Marginal PASS”; else cout << “FAIL”; FAIL is printed; WHY? The compiler ignores indentation and pairs the else with the second if average 100.0

if.. else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE if clauseelse clause expression

What happens if you omit braces? if ((carDoors == 4) && (driverAge > 24)) premium = ; cout << “ LOW RISK “; else premium = ; cout << “ HIGH RISK ”; monthlyPayment = premium / ; Compile error occurs: The “if clause” is the single statement following the if

Example  Given x, y on Cartesian plane, which quadrant is it in? (I, II, III, IV) if (x > 0) if (y > 0) quadrant = 1; else quadrant = 4; else if (y > 0) // NOT a redundant test! quadrant = 2; else quadrant = 3;

Another form of nested if's if (condition) statement; else if (condition) statement; else if (condition) statement; else statement; // good for mutually exclusive and exhaustive conditions

Comparing Strings Two objects of type string (or a string object and a C string) can be compared using the relational operators A character-by-character comparison is made using the ASCII character set values If all the characters are equal, then the 2 strings are equal. Otherwise, the string with the character with smaller ASCII value is the “lesser” string

string myState; string yourState; myState = “Texas”; yourState = “Maryland”; ExpressionValue myState == yourState false myState > yourState true myState == “Texas”true myState < “texas”true

Testing code needs to be tested in every possible branch takes multiple runs test plans CaseInputOutput (expected) Output (actual)

Test Plan if (x + y > 0) cout << "safe"; else if (x > 3) cout << "high"; else cout << "low";

Test Plan CaseInputOutput (expected) Output (actual) x + y > 0x = 5, y = 7"safe" x + y 3 x = 5, y=-7"high" x+y <=0, x <= 3 x = 2, y=-3"low"

Comparing Real Values Do not compare floating point values for equality, compare them for near-equality. float myNumber; float yourNumber; cin >> myNumber; cin >> yourNumber; if (fabs (myNumber - yourNumber) < ) cout << “They are close enough!” << endl;