Chapter 7 Conditional Statements

Slides:



Advertisements
Similar presentations
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Advertisements

1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Copyright 2003 Scott/Jones Publishing Making Decisions.
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.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
A First Book of C++ Chapter 4 Selection.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 3 Selection Statements
Chapter 4: Control Structures I (Selection)
CNG 140 C Programming (Lecture set 3)
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Control Structures – Selection
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Expression Review what is the result and type of these expressions?
Chapter 4: Control Structures I (Selection)
Additional Control Structures
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Structured Program Development in C++
Boolean Variables and Expressions
Selection Control Structure
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Controlling Program Flow
Presentation transcript:

Chapter 7 Conditional Statements

7.1 Conditional Expressions Condition – any expression that evaluates to true/false value <expr1> <relational_operator> <expr2> Relational operators are BINARY X < 4 Y == a+b q+1 != s*2

7.1.1 Relational Operators Relational Operator Description == Equality (be sure to use two equal signs) * != Inequality < Less than > Greater than <= Less than or equal to >= Greater than or equal to * Single equal sign (=) is an assignment / does NOT compare values

7.1.1 Relational Operators const int CONST_iEXP = 9; int iexp1 = 0, iexp2 = 5; float fexp = 9.0; char cexp = 'a'; bool result = true; result = iexp1 == 0; // true result = iexp2 >= iexp1; // true result = iexp1 > CONST_iEXP; // false result = fexp == CONST_iEXP; // true result = cexp <= iexp1; // false result = iexp1 != iexp2; // true result = cexp == 'a'; // true

7.1.1 Relational Operators // ----- ILLEGAL OR MALFORMED CONDITIONS ---- result = 3 < X < Y; // Malformed condition. What does it mean? // 3 < X and X < Y ??? // 3 < X or X < Y ??? cexp == "a"; // Illegal. Attempting to compare a character // to a string literal.

7.1.2 Logical Operators Logical operators - combine bool expressions or: x || y (binary operator) false only when both operands are false and: x && y (binary operator) true only when both operands are true not: !x (unary operator) false when operand is true; otherwise true.

7.1.2 Logical Operators Truth table - displays Boolean results produced when the operator is applied to specified operands Logical AND and OR truth table Condition c1 Condition c2 c1 && c2 c1 || c2 true false

7.1.2 Logical Operators Logical NOT truth table ! (not) && (and) Order of precedence ! (not) && (and) || (or) Condition c !c true false

7.1.2 Logical Operators Misc Information: Parentheses change the precedence Parentheses can help clarify complicated conditions Short-circuit evaluation - once the outcome of condition can be determined, evaluation ends

7.1.2 Logical Operators Various logical operators int iexp1 = 0, iexp2 = 5; float fexp = 9.0; char cexp = 'a'; const int CONST_iEXP = 9; bool result; result = iexp1 < iexp2 && fexp == 9.0; result = iexp1 > CONST_iEXP || fexp == 9.0; // true result = !(fexp == 9.0 || iexp1 > CONST_iEXP);// false // Short-Circuit Evaluation result = fexp == 9.0 || iexp1 > CONST_iEXP; // true

7.2 The if Statement Selects actions to be taken only when a specific condition is satisfied Syntax: if ( <condition> ) <action> Example: if ( N % 2 == 1) cout << N << “ is ODD” << endl;

7.2 if (<condition>) <action> <condition> - a valid expression that can be interpreted as a TRUE/FALSE value Relational expression (e.g., x <= 2) Logical expression ( x>5 && y != 2) Integer-valued expression: 0=false; otherwise true. <action> - a valid C++ statement or block Single statement terminated with semicolon Compound statement (block) enclosed in set braces { } if (Age > 21) if (Income > 24000) Sell_Beer = true; { SSTax = 0.05 * Income; FedTax = 0.075 * Income; }

7.2 The if Statement if (condition) statement; // Example 1 if ( test >= 80 && test < 90 ) cout << "You have earned a B" << endl; // Example 2 – relational expression/compound statement. if ( test >= 90 ) { cout << "You have earned an A" << endl; cout << "Excellent work!" << endl; } // Example 3 – logical expression/compound statement. if ( test >= 70 && test < 80 ) cout << "You have earned a C" << endl;

7.2.1 The else Statement Optional part of an if statement Can’t stand alone Must be associated with an open if if ( <condition> ) <action 1> // Consequence (true-part) else <action 2> // Alternative (false-part) Means: “otherwise”, “catch-all”, “none of the above”

7.2.1 The else Statement else <action> // consequence. no condition or expression associated with it relies on the value of the condition associated with the previous if (or chain of ifs) executes action(s) only if the previous condition (or chain of ifs) is false if more than one statement, the action must be enclosed in curly braces

7.2.1 The if-else Statement else Example if ( grade >= 60 ) pass = true; else { pass = false; cout << "Hope you do better next time" << endl; }

7.2.1 Multiple alternative if The alternative of an if is another decision: if ( avg >= 90 ) cout << “Grade = A" << endl; else if ( avg >= 80 ) cout << "B" << endl; -------- NOTE indentation. else if ( avg >= 80 )

7.2.1 Selecting from multiple alternatives Only ONE action is selected from a chain of decisions. if ( Avg >= 90 ) Grade = ‘A’; else if ( Avg >= 80 ) Grade = ‘B’; else if ( Avg >= 70) Grade = ‘C’; else if ( Avg >= 60) Grade = ‘D’; else // Optional Grade = ‘F’; NOTE: The construct terminates when a choice is made. QUESTIONS: # of decisions needed to assign A? C? F?

7.2.1 Sequence of if statements Inefficient: how many decisions for A, C, F? if ( avg >= 90 ) cout << "A" << endl; if ( avg >= 80 && avg < 90 ) cout << "B" << endl; if ( avg >= 70 && avg < 80 ) cout << "C" << endl; if ( avg >= 60 && avg < 70 ) cout << "D" << endl; if ( avg < 60 ) cout << "F" << endl;

7.2.1 Multiple-alternative chain of if Mutual exclusion: result can be only one of the choices if ( avg >= 90 ) cout << "A" << endl; else if ( avg >= 80 ) cout << "B" << endl; else if ( avg >= 70 ) cout << "C" << endl; else if ( avg >= 60 ) cout << "D" << endl; else cout << "F" << endl; 90 80 70 60

7.2.1 Multiple alternative if chain Notes: Each condition is tried until one is satisfied (i.e., value is true) The matching consequence is executed The decision process terminates the

7.2.1 The Nested if construct Nested  the consequence is itself a decision. if ( gpa >= 3.75 ) if ( credits > 25 ) if ( money < 30000 ) { scholarship = 5000; cout << "Way to go!" << endl; } else scholarship = 2000; scholarship = 1000; { scholarship = 0; cout << "You're on your own." << endl;

7.3 Variable Scope Scope of a variable – determines: What code can access or change the variable How long the variable exists or lives

7.3 Variable Scope Below, var_a and var_b defined within the scope of the block Both accessible within the block where defined Final line generates an error message - var_b is not defined { int var_a = 5, var_b = 10; var_a++; cout << "var_a: " << var_a << endl; } cout << "var_b: " << var_b; // Error: undeclared // identifier var_b

7.3 Variable Scope Local scope – variables or constants declared within braces

7.3 Variable Scope Constant PI and variable global_area - physically declared outside of function - placed at the global level #include <iostream> using std::cout; using std::endl; #include <cmath> // Needed for pow const float PI = 3.141592F; // global scope float global_area = 0; // global scope int main() { float radius = 5; // local scope global_area = static_cast<float>( PI * pow( radius, 2 ) ); cout << global_area << " sq. in." << endl; return 0; } // Output 78.5398 sq. in.

7.3 Variable Scope Any code within the file can access PI or global_area #include <iostream> using std::cout; using std::endl; #include <cmath> // Needed for pow const float PI = 3.141592F; // global scope float global_area = 0; // global scope int main() { float radius = 5; // local scope global_area = static_cast<float>(PI * pow(radius, 2)); cout << global_area << " sq. in." << endl; return 0; } // Output 78.5398 sq. in.

7.3 Variable Scope Global variables - automatically initialized to 0 Avoid global variables (i.e., global_area) #include <iostream> using std::cout; using std::endl; #include <cmath> // Needed for pow const float PI = 3.141592F; // global scope float global_area = 0; // global scope int main() { float radius = 5; // local scope global_area = static_cast<float>(PI * pow(radius, 2)); cout << global_area << " sq. in." << endl; return 0; } // Output 78.5398 sq. in.

7.4 The switch Statement switch statement - another form of conditional statement Also called a selection statement Checks only for equality and only for one variable

7.4 The switch Statement Works well for checking a variable for limited set of values Only works with ordinal data types Ordinal data types - can be translated into an integer to provide a finite, known, number set Examples include int, bool, char, and long

7.4 The switch Statement General form of the switch statement: switch( <variable> ) { // Required case <literal or const 1>: <action 1> break; case <literal or const 2>: <action 2> ... default: // Optional <default action> }// Required When first line is encountered, value of the variable determined Execution jumps to the case which corresponds to the value of the variable being examined Execution continues until either a break statement is encountered or to the end of switch

7.4 The switch Statement break statement - stops execution of the control structure prematurely Stops multiple case statements from being executed Many believe poor programming to use outside the context of the switch statement

7.4 The switch Statement default statement - executed if value of the variable doesn’t match any of previous cases Type of catch all or “case else” Technically can use the default case in any position Should physically be the last one in the switch statement

7.4 The switch Statement int menu_item = 0; ... switch ( menu_item ) { case 1: // Using literal values cout << "You have chosen option 1." << endl; break; case 2: cout << "You have chosen option 2." << endl; case 3: cout << "You have chosen option 3." << endl; default: cout << "Invalid menu option." << endl; }

7.4 The switch Statement const short GREEN = 0; const short YELLOW = 1; const short RED = 2; short light_color = GREEN; switch ( light_color ) { case GREEN: // Using constants cout << "Go!" << endl; break; case YELLOW: // Let fall through case RED: cout << "Stop!"; cout << "Proceed when light is green." << endl; default: cout << "Power is out!" << endl; }

7.4 The switch Statement char letter_grade; cout << "Enter letter grade: "; cin >> letter_grade; switch ( letter_grade ) { case 'A': // Using character literal values cout << "Excellent!" << endl; break; case 'B': cout << "Above average." << endl; case 'C': cout << "Average." << endl; case 'D': cout << "Below average." << endl; case 'F': cout << "Failed!" << endl; default: cout << "Invalid letter grade." << endl; }

7.4 The switch Statement One of the most common uses of switch statement is in menu driven programs Student Grade Program - Main Menu - 1. Enter name 2. Enter test scores 3. Display test scores 9. Exit Please enter your choice from the list above:

7.5 Conditional Operator Conditional operator - considered a ternary operator, meaning it has three operands Syntax: <condition> ? <true expression> : <false expression>

7.5 Conditional Operator One of the expressions is returned based upon the evaluation of the condition int a = 5, b = 0; int larger = a > b ? a : b; cout << larger << endl; // Output 5

7.5 Conditional Operator Equivalent if statement to code on previous page int a = 5, b = 0; int larger; if ( a > b ) larger = a; else larger = b;

7.5 Conditional Operator More challenging conditional operator example short hour = 9, minute = 10, second = 5; cout << (hour < 10 ? "0" : "") << hour << ":" << (minute < 10 ? "0" : "") << minute << ":" << (second < 10 ? "0" : "") << second << endl; // Output 09:10:05 Empty quotes above tell cout to print nothing if the condition is false (i.e. hour is 10 or greater)