Download presentation
Presentation is loading. Please wait.
1
Chapter 7 Conditional Statements
2
7.1 Conditional Expressions
Conditions Compare the values of variables, constants and literals using one or more relational operators Binary operators A variable, constant, or literal must appear on each side of the operator The comparison determines whether the expression is true or false Remember: A constant is similar to a variable except the value can’t change. A literal is a number, character or string without a name associated with it.
3
7.1.1 Relational Operators – Options
Description == Equality (be sure to use two equal signs) != Inequality < Less than > Greater than <= Less than or equal to >= Greater than or equal to Important Single equal sign (=) is an assignment Double equal sign (==) tests for equality Remember: A single equal sign (=) is an assignment and a double equal sign (==) represents a test for equality.
4
7.1.1 Relational Operators – Example
const int CONST_INT_EXP = 9; int int_exp1 = 0, int_exp2 = 5; float float_exp = 9.0; char char_exp = 'a'; bool result; result = int_exp1 == 0; // true result = int_exp2 >= int_exp1; // true result = int_exp1 > CONST_INT_EXP; // false result = float_exp == CONST_INT_EXP; // true result = char_exp <= int_exp1; // false, remember ASCII values? result = int_exp1 != int_exp2; // true result = char_exp == 'a'; // true // ILLEGAL OR MALFORMED CONDITIONS // Malformed condition. May or may not compile depending on compiler used. Even if the compiler // will compile this condition, it should NEVER be written in this manner. result = int_exp1 < int_exp2 < float_exp; // Illegal. Attempting to compare a character to a string literal. result = char_exp == "a"; Remember: The ASCII table shows the association between a character and a number. The number is how the character is stored in memory and therefore is used in the comparison. See Appendix B for an ASCII chart.
5
7.1.2 Logical Operators – Options
Combine multiple relational operators into a larger composite condition Operators || (OR) - binary operator False value only if the conditions on each side of the operator are false && (AND) - binary operator Results in a true value only if the condition on both sides of the operator are true ! (NOT) - unary operator Reverses logic of the single condition
6
7.1.2 Logical Operators – Truth Table
Displays Boolean results produced when the operator is applied to specified operands Condition 1 Condition 2 && Result || Result true false Condition ! Result true false
7
7.1.2 Logical Operators – Order of Precedence
&& operator evaluated before the || operator The ! operator Highest level of precedence of all logical operators and is higher than the relational operators Parentheses change the precedence Parentheses can help clarify complicated conditions Short-circuit evaluation Once the outcome of condition can be determined, evaluation ends
8
7.1.2 Logical Operators – Example
int int_exp1 = 0, int_exp2 = 5; float float_exp = 9.0; char char_exp = 'a'; const int CONST_INT_EXP = 9; bool result; result = int_exp1 < int_exp2 && float_exp == 9.0; // true result = int_exp1 > CONST_INT_EXP || float_exp == 9.0; // true result = !(float_exp == 9.0 || int_exp1 > CONST_INT_EXP); // false // Short-Circuit Evaluation result = float_exp == 9.0 || int_exp1 > CONST_INT_EXP; // true
9
7.2 The if Statement – Syntax
Uses conditions to determine a specific action if ( <condition> ) <action> <condition> Any valid expression, either built from relational and logical operators or from evaluation of a single variable Zero is false while any non-zero value is considered true Any valid C++ statement Multiple statements must be enclosed in curly braces { }
10
7.2 The if Statement – Example
// Example 1 if ( test >= 80 && test < 90 ) cout << "You have earned a B" << endl; // Example 2 if ( test >= 90 ) { // Start of the action block cout << "You have earned an A" << endl; cout << "Excellent work!" << endl; } // End of the action block // Example 3 if ( test >= 70 && test < 80 ) { // Start of the action block cout << "You have earned a C" << endl;
11
7.2.1 The else Statement – Syntax
Optional part of if statement Can’t stand alone and must be associated with an if No condition or expression associated with it Relies on results of the condition associated with the if Executes action(s) only if the condition is false Action can contain one or more statements If more than one statement, the action must be enclosed in curly braces if ( <condition> ) <action 1> else <action 2>
12
7.2.1 The else Statement – Example
if ( grade >= 60 ) pass = true; else { pass = false; cout << "Hope you do better next time" << endl; }
13
7.2.2 The else if Statement – Nested if
Embedding another if in action block of the else if ( avg >= 90 ) cout << "A" << endl; else if ( avg >= 80 ) cout << "B" << endl; Nested if indentation can cause the code to become difficult to read
14
7.2.2 The else if Statement – Syntax
else if syntax if ( <condition 1> ) <action 1> else if ( <condition 2> ) <action 2> else if ( <condition 3> ) <action 3> . . . else // Optional <last action> Remember: The else is always optional and must be placed at the end of the if statement.
15
7.2.2 The else if Statement – Inefficient if
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; How many conditions are evaluated if avg equals 90? 8 How many conditions are evaluated if avg equals 60?
16
7.2.2 The else if Statement – Efficient if
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; How many conditions are evaluated if avg equals 90? 1 How many conditions are evaluated if avg equals 60? 4
17
7.2.2 The else if Statement – Flowchart
18
7.2.2 The else if Statement – Nested Control Statements
Has another control statement in its action block if ( gpa >= 3.75 ) if ( credits > 25 ) if ( money < ) { scholarship = 5000; cout << "Way to go!" << endl; } else scholarship = 2000; scholarship = 1000; scholarship = 0; cout << "You're on your own." << endl;
19
7.3 Variable Scope – Definition
Scope of a variable Determines what code can access or change the variable Determines how long the variable exists or lives Local scope Variables or constants declared within braces Global scope Variables or constants declared outside of any enclosing braces, usually above main Automatically initialized to 0 Avoid global variables
20
7.3 Variable Scope – Example
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; } // Error: undeclared identifier var_b cout << "var_b: " << var_b;
21
7.3 Variable Scope – Global Identifiers
PI and variable global_area are 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 = F; // 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 sq. in.
22
7.4 The switch Statement – Definition
Another form of conditional statement Also called a selection statement Checks only for equality and only for one variable 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
23
7.4 The switch Statement – Syntax
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
24
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
25
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
26
7.4 The switch Statement – Example with Literals
int menu_item = 0; switch ( menu_item ) { case 1: 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; }
27
7.4 The switch Statement – Example with Constants
const short GREEN = 0; const short YELLOW = 1; const short RED = 2; short light_color = GREEN; switch ( light_color ) { case GREEN: 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; }
28
7.4 The switch Statement – Example with Characters
char letter_grade; cout << "Enter letter grade: "; cin >> letter_grade; switch ( letter_grade ) { case 'A': cout << "Excellent!\n"; break; case 'B': cout << "Above average.\n"; case 'C': cout << "Average.\n"; break; case 'D': cout << "Below average.\n"; case 'F': cout << "Failed!\n"; default: cout << "Invalid grade.\n"; } Remember: It is only possible to use a switch statement with integers or single characters.
29
7.4 The switch Statement – Common Use
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: Remember: You must include the entire body of the switch statement within braces.
30
7.5 Conditional Operator – Definition
Considered a ternary operator, meaning it has three operand Syntax <condition> ? <true expression> : <false expression> One of the expressions is returned based upon the evaluation of the condition
31
7.5 Conditional Operator – Example
int a = 5, b = 0; int larger = a > b ? a : b; cout << larger << endl; // Output 5 Equivalent code int a = 5, b = 0; int larger; if ( a > b ) larger = a; else larger = b; cout << larger << endl;
32
7.5 Conditional Operator – More Complex Example
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)
33
7.7 C The Differences – Boolean
Older versions of C did not have a Boolean data type There wasn’t a predefined true or false All relational operators return either a zero for false or a non-zero value, usually one, for true The C99 version of the ANSI Standard includes a Boolean data type #define BOOL int #define FALSE 0 #define TRUE !FALSE int main ( void ) { BOOL done = FALSE; return 0; } C programmers often made their own data type similar to what is show to the left
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.