Chapter 7 Conditional Statements C LEARN BY DOING

Chapter 7 Conditional Statements C++: LEARN BY DOING Todd Breedlove Troy Scevers Randal L. Albert

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

7. 1. 1 Relational Operators – Options 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 Important • Single equal sign (=) is an assignment • Double equal sign (==) tests for equality

7. 1. 1 Relational Operators – Example const int CONST_INT_EXP = 9; int_exp 1 = 0, int_exp 2 = 5; float_exp = 9. 0; char_exp = 'a'; bool result; result result = = = = int_exp 1 == 0; int_exp 2 >= int_exp 1; int_exp 1 > CONST_INT_EXP; float_exp == CONST_INT_EXP; char_exp <= int_exp 1; int_exp 1 != int_exp 2; char_exp == 'a'; // // true false, remember ASCII values? 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_exp 1 < int_exp 2 < float_exp; // Illegal. Attempting to compare a character to a string literal. result = char_exp == "a";

7. 1. 2 Logical Operators – Options • Logical operators • 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

7. 1. 2 Logical Operators – Truth Table • Truth table • Displays Boolean results produced when the operator is applied to specified operands Condition 1 true false Condition 2 true false && Result true false || Result true false Condition ! Result true false true

7. 1. 2 Logical Operators – Order of Precedence • 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

7. 1. 2 Logical Operators – Example int_exp 1 = 0, int_exp 2 = 5; float_exp = 9. 0; char_exp = 'a'; const int CONST_INT_EXP = 9; bool result; result = int_exp 1 < int_exp 2 && float_exp == 9. 0; // true result = int_exp 1 > CONST_INT_EXP || float_exp == 9. 0; // true result = !(float_exp == 9. 0 || int_exp 1 > CONST_INT_EXP); // false // Short-Circuit Evaluation result = float_exp == 9. 0 || int_exp 1 > CONST_INT_EXP; // true

7. 2 The if Statement – Syntax • if statement • 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 • <action> • Any valid C++ statement • Multiple statements must be enclosed in curly braces { }

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; } // End of the action block

7. 2. 1 The else Statement – Syntax • else statement • 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>

7. 2. 1 The else Statement – Example if ( grade >= 60 ) pass = true; else { pass = false; cout << "Hope you do better next time" << endl; }

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 cause the code to become difficult to read

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>

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? 6

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

7. 2. 2 The else if Statement – Flowchart

7. 2. 2 The else if Statement – Nested Control Statements • Nested control statement • Has another control statement in its action block if ( gpa >= 3. 75 ) if ( credits > 25 ) if ( money < 30000 ) { scholarship = 5000; cout << "Way to go!" << endl; } else scholarship = 2000; else scholarship = 1000; else { scholarship = 0; cout << "You're on your own. " << endl; }

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

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;

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 = 3. 141592 F; 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 – Definition • switch statement • 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

7. 4 The switch Statement – Syntax switch( <variable> ) { // Required case <literal or const 1>: <action 1> break; case <literal or const 2>: <action 2> break; . . . 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 • 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 • 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 – 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; break; case 3: cout << "You have chosen option 3. " << endl; break; default: cout << "Invalid menu option. " << endl; }

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; break; default: cout << "Stop!"; cout << "Power is out!" << endl; }

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"; break; case 'C': cout << break; case 'D': cout << break; case 'F': cout << break; default: cout << } "Average. n"; "Below average. n"; "Failed!n"; "Invalid grade. n";

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. 2. 3. 9. Enter name Enter test scores Display test scores Exit Please enter your choice from the list above:

7. 5 Conditional Operator – Definition • Conditional operator • 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

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;

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)

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 C 99 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
- Slides: 33