Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by making a choice): Executes certain statements depending on some condition(s). 3. Repetition (loops) : Repeats particular statements a certain number of times depending on some condition(s). B. Examples of Conditional Statements 1. if ( score is greater than or equal to 90 ) grade is A 2. if ( hours worked are less than or equal to 40 ) wages = rate * hours otherwise wages = (rate * 40) + 1.5 * (rate * (hours - 40)) 3. if (temperature is greater than 70 degrees and it is not raining) recommended activity is golfing NOTICE: Certain statements will be executed only if the stated conditions are met. In other words, if the statement is true, the following statement is executed. In example 3, more than one condition must be met: a temperature greater than 70 AND no rain. Conditional statements can have one or more parts. If the statement is false, the statement is skipped or ignored or another statement is executed instead, as in example 2. II. Relational Operators A. Logical (Boolean) Expression: An expression that evaluates to true or false. 1. Logical (Boolean) Values: True or False Page 1
2. Relational Operators: Allow the programmer to make comparisons in a program. Arithmetic Operation Relational Operator Meaning = = = Is equal to < < Is less than > > Is greater than <= Is less than or equal to >= Is greater than or equal to!= Is NOT equal to 3. Each of the Relational Operators is a binary operator, because they are suppose to be comparing two values. B. Relational Operators and Simple Data Types 1. Relational Operators can be used on all three simple data types. Expression Meaning Value 8 < 15 8 is less than 15 true 6!= 6 6 is not equal to 6 false 2.5 > 5.8 2.5 is greater than 5.8 false 5.9 <= 7.5 5.9 is less than or equal to 7.5 true WARNING: The comparison of real numbers for equality is usually machine dependent. It is quite possible that on a particular machine 6.8 + 3.1 = = 2.7 + 7.2 will evaluate to false. 2. Relational Operators and the char Data Type i. When a character is evaluated with a relational operator, the character is normally converted to its integer equivalent on the ASCII chart. Both characters being compared are then converted to integers and the integers compared for equality, inequality, greater than, etc. Page 2
Expression Value of Expression Explanation ' ' < 'a' 'R' > 'T' '+' < '*' '6' <= '>' true false false true The ASCII value of ' ' is 32, and the ASCII value of 'a' is 97. Because 32 < 97 is true, it follows that ' ' < 'a' is true. The ASCII value of 'R' is 82, and the ASCII value of 'T' is 84. Because 82 > 84 is false, it follows that 'R' < 'T' is false. The ASCII value of '+' is 43, and the ASCII value of '*' is 42. Because 43 < 42 is false, it follows that ' + ' < ' * ' is false. The ASCII value of ' 6 ' is 54, and the ASCII value of ' > ' is 62. Because 54 <= 62 is true, it follows that ' 6 ' < ' > ' is true. 3. You should not use comparisons of different data types in your program because the results may be unpredictable. 4. More on Boolean Values: In C++, the Boolean value of true is actually returned as a one (1), while the Boolean value for false is actually returned as a zero (0). Actually, any number that is not zero is accounted as true in C++ Boolean values, but only a zero is accounted as false. C. Relational Operators and the string Type 1. Relational Operators Can be Applied to the string Type 2. Strings are compared character by character, starting with the first character and using the ASCII collating sequence. 3. Character by character comparison continues until either a mis-match is found or the last characters have been compared and are equal. 4. Assume that a program has made the following data declarations: Page 3
string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; string str5 = "Big"; Now we can look at the following table using the above declarations to determine how Logical Expressions work with Strings and String Variables. Expression str1 < str2 str1 > "Hen" str3 < "An" str1 = = "hello" str3 <= str4 Value true false true false true 5. Comparing Two Strings of Different Length i. Comparison is made character by character until it reaches the last character of the shorter string. If all characters have been equal, the string with the fewer characters is deemed to be less than the larger string. Examples using the same declared strings above. Expression str4 >= "Billy" str5 <= "Bigger" Value false true III. Logical (Boolean) Operators and Logical Expressions A. Logical (Boolean) Operators in C++ 1. Logical (Boolean) Operators allow the programmer to combine logical expressions. 2. C++ has three Logical (Boolean) Operators as follows: Page 4
Operator Description Type Operator! not unary - Require only one operand && and binary - Require two operands or binary - Require two operands 3. Logical operators take only logical values as operands and yield only logical values as results. 4. The! (not) Operator: Putting! in front of a logical expression reverses its value. So!(true) = false, and!(false) = true Expression Value Explanation! ( 'A' > 'B' ) true Because 'A' > 'B' is false,! ( 'A' > 'B' ) is true! ( 6 <= 7 ) false Because 6 <= 7 is true,! ( 6 <= 7 ) is false 5. The && (and) Operator: Expression A Expression B Expression A && Expression B true true true true false false false true false false false false Examples: Expression Value Explanation ( 14 >= 5 ) && ( 'A' < 'B' ) true ( 24 >= 35 ) && ( 'A' < 'B' ) false Because ( 14 >= 5 ) is true, ( 'A' < 'B' ) is true, and true && true is true, the expression evaluates to true. Because ( 24 >= 35 ) is false, ( 'A' < 'B' ) is true, and false && true is false, the expression evaluates to false. Page 5
Notice: The && (and) expression is true only when both expressions are true. Only one false expression renders the entire expression false. 6. The (or) Operator: Expression A Expression B Expression A Expression B true true true true false true false true true false false false Examples: Expression Value Explanation ( 14 >= 5 ) ( 'A' > 'B' ) true ( 24 >= 35 ) ( 'A' > 'B' ) false ( 'A' <= 'a' ) ( 7!= 7 ) true Because ( 14 >= 5 ) is true, ( 'A' > 'B' ) is false, and true false is true, the expression evaluates to true. Because ( 24 >= 35 ) is false, ( 'A' > 'B' ) is false, and false false is false, the expression evaluates to false. Because ( 'A' >= 'a' ) is true, ( 7!= 7 ) is false, and true false is true, the expression evaluates to true. Notice: The (or) expression is false only when both expressions are false. Only one true expression renders the entire expression true. B. Order of Precedence: Complex logical expressions can be difficult to evaluate, so an order of precedence is necessary for them also. Page 6
1. An expression like the following can yield more than one answer if evaluated in different orders: 11 > 5 6 < 15 && 7 >= 8 T T && F T && F = F (or) evaluated first T F = T (and) evaluated first Precedence of Operators Operators Precedence!, +, - (unary operators) first *, /, % second +, - third <, <=, >=, > fourth = =,!= fifth && sixth seventh = (assignment operator) last Suppose you have the following declarations: bool found = true, flag = false ; int num = 1; double x = 5.2, y = 3.4; int a = 5, b = 8, n = 20 ; char ch = 'B' ; Page 7
Examples using the above declarations: Expression Value Explanation!found false Because found is true,!found is false x > 4.0!num!found && ( x >= 0 ) true false false Because x is 5.2 and 5.2 > 4.0 is true, the expression x > 4.0 evaluates to true. Because num is 1, which is nonzero, num is true and so!num is false. In this expression,!found is false. Also, because x is 5.2 and 5.2 >= 0 is true, x >= 0 is true. Therefore, the value of the expression!found && (x >= 0) is false && true, which evaluates to false.!( found && ( x >= 0 ) ) false In this expression, found && ( x >= 0 ) is true && true, which evaluates to true. Therefore, the value of the expression!( found && ( x >= 0 )) is!true, which evaluates to false. x + y <= 20.5 true Because x + y = 5.2 + 3.4 = 8.6 and 8.6 <= 20.5, it follows that x + y <= 20.5 evaluates to true. ( n >= 0 ) && ( n <= 100 ) true ( 'A' <= ch && ch <= 'Z' ) true ( a + 2 <= b ) &&!flag true Here n is 20. Because 20 >= 0 is true, n >= 0 is true. Also, because 20 <= 100 is true, n <= 100 is true. Therefore, the value of the expression ( n >= 0 ) && ( n <= 100 ) is true && true, which evaluates to true. In this expression, the value of ch is 'B'. Because 'A' <= 'B' is true, 'A' <= ch evaluates to true. Also, because 'B' <= 'Z' is true, ch <= 'Z' evaluates to true. Therefore, the value of the expression ( 'A' <= ch && ch <= 'Z' ) is true && true, which evaluates to true. Now a + 2 = 5 + 2 = 7 and b is 8. Because 7 < 8 is true, the expression a + 2 < b evaluates to true. Also, because flag is false,!flag is true. Therefore, the value of the expression ( a + 2 <= b ) &&!flag is true && true, which evaluates to true. Page 8
C. Short-Circuit Evaluation 1. In C++, if the first value in an AND (&&) expression is false, it does not continue to evaluate the other side of the expression. It immediately evaluates to false. 2. Similarly, if the first value in an OR ( ) expression is true, it does not evaluate the right side but returns a true for the whole expression. D. The int Data Type and Logical (Boolean) Expressions 1. It is possible to store the value of a logical expression into an int data type variable. 2. Recall that false is counted as zero ( 0 ), and true is a one (1 ) or any nonzero value. 3. The following snippet of code illustrates how this can work. int legalage ; int age ; age = 21 ; legalage = ( age >= 21 ) ; The value of one ( 1 ) is assigned to legalage since age is equal to 21 and is greater than or equal to 21. The value of zero ( 0 ) would have been assigned to legalage had age been less than 21. IV. Selection: if and if... A. Branch Control Structures 1. There are two types of branch control structures that will be talked about in this chapter. i. The if and if... statements which can be used to create oneway, two-way, and multi-way selection statements. ii. The switch statement Page 9
B. One-Way Selection: If true, execute statement immediately following the logical expression. If false, skip that statement. 1. Syntax and Use: if ( logical expression ) statement ; Example: if ( score >= 90 ) grade = 'A' ; If the expression score >= 90 evaluates to true, the character 'A' is stored in grade. If the expression is false, the statement grade = 'A' is completely skipped or ignored. 2. Example of a program with a one-way selection statement: The following C++ program finds the absolute value of an integer #include <iostream> using namespace std; int main ( ) int number ; cout << "Please enter an integer > " ; cin >> number ; if ( number < 0 ) number = - number ; cout << endl << "The absolute value is " << number << endl ; system("pause") ; return 0 ; OUTPUT Please enter an integer > -6734 The absolute value is 6734 Page 10
3. Two Common Mistakes i. Leaving out the parenthesis: a. if score >= 90 Syntax error!! grade = 'A' ; b. Your compiler should let you know about this. ii. Putting a Semicolon after the Logical Expression: a. if ( score >= 90 ) ; Semantic error!! grade = 'A' ; b. Your compiler will not let you know about this!! C. Two-Way Selection: If true, execute statement immediately following the logical expression. If false, the statement immediately following the reserved word is executed. 1. Syntax and Use: if ( logical expression ) statement 1; statement 2; Example : if ( hours > 40.0 ) wages = 40.0 * rate + 1.5 * rate * ( hours - 40.0) ; wages = hours * rate ; 2. Sample Program: #include <iostream> #include <iomanip> using namespace std; int main ( ) double wages, rate, hours ; Page 11
cout << fixed << showpoint << setprecision(2) ; cout << Enter working hours and rate: ; cin >> hours >> rate ; if ( hours > 40.0 ) wages = 40.0 * rate + 1.5 * rate * ( hours - 40.0) ; wages = hours * rate ; cout << endl ; cout << The wages are $ << wages << endl ; system( pause ) ; return 0 ; OUTPUT Enter working hours and rate: 56.45 12.50 The wages are $808.44 3. Common Semantic Errors i. Consider the following statement: if ( score >= 90 ) grade = 'A' ; cout << "The grade is " << grade << endl; The if statement acts only on the grade = 'A' ; statement. Just because the other statement is indented doesn't make it apart of the if statement. The cout statement will execute regardless of whether the if statement is true or false. ii. Another common mistake is assuming the second statement will execute if the first one is false. Example: if ( score >= 60 ) cout << "Passing" << endl ; cout << "Failing" << endl; In this case, if the score is greater than 60, both lines of code will Page 12
execute. If you want the second statement to execute if the condition is false, or only the first statement to execute when the condition is true, you must use the if... statement like so: if ( score >= 60 ) cout << "Passing" << endl ; cout << "Failing" << endl ; D. Compound (Block of) Statements: A sequence of statements enclosed in curly braces that functions as if it were a single statement. 1. Syntax and Use: statement 1 ; statement 2 ; : : statement n ; 2. Use compound ( block of ) statements in a conditional statement when you want more than one statement to execute if the condition is true or if the condition is false in an if... statement. Example: #include <iostream> using namespace std; int main ( ) int age ; cout << "Please enter your age here: " << endl ; cin >> age; if ( age > 18 ) cout << "Eligible to vote." << endl ; cout << "No longer a minor." << endl ; Page 13
cout << "Not eleigible to vote." << endl ; cout << "Still a minor." << endl ; system("pause") ; return 0 ; OUTPUT Please enter your age here: 16 Not eligible to vote. Still a minor. Press enter to continue... E. Multiple Selections: Nested if: Used when more than two choices need to be made. 1. In a one-way selection ( if ), if the condition is true, the following statement is executed; false, and it isn't. A two-way selection ( if... ) executes one of two statements depending if the statement is true or false. With a multiple selection statement ( nested if statements ), a number of statements can be chosen from to execute depending on the which of the nested if statements is true. 2. Syntax and Use: if ( logical expression ) statement 1; if ( logical expression ) statement 2; if ( logical expression ) statement 3; : : statement n ; Page 14
OR if ( logical expression ) statement 1 ; if ( logical expression ) statement 2 ; if ( logical expression ) statement 3 ; : : statement n ; 3. Example Program using multiple selections: #include <iostream> using namespace std ; int main ( ) int score ; cout << "Please enter a score here: " ; cin >> score ; if ( score >= 90 ) cout << "The grade is A" << endl ; if ( score >= 80 ) cout << "The grade is B" << endl ; if ( score >= 70 ) cout << "The grade is C" << endl ; if ( score >= 60 ) cout << "The grade is D" << endl ; cout << "The grade is F" << endl ; system("pause") ; return 0 ; 4. Pairing an With an if i. It can be confusing in a nested if statement to determine which if the statement refers to. Page 15
ii. The Rule: In nested if statements, C++ associates the with the most recent incomplete if, or, in other words, the most recent if that has not been paired with an. F. Comparing if... Statements with a Series of if Statements 1. An if.. statement, if done properly, can be rewritten as a series of individual if statements. 2. A series of individual if statements, if done properly, can be rewritten as a single if.. statement. 3. So what is the difference between them? Example of a series of if statements and an if.. statement that performs the exact same evaluation and output. #include <iostream> using namespace std; int main ( ) int month ; cout << "Please enter integer from 1 to 6: " ; cin >> month ; if ( month = = 1 ) cout << "January" << endl ; if ( month = = 2 ) cout << "February" << endl ; if ( month = = 3 ) cout << "March" << endl ; if ( month = = 4 ) cout << "April" << endl ; if ( month = = 5 ) cout << "May" << endl ; if ( month = = 6 ) cout << "June" << endl ; system("pause") ; return 0 ; OUTPUT Page 16
Please enter integer from 1 to 6: 5 May Now let's see the same program using the nested if.. statements... #include <iostream> using namespace std; int main ( ) int month ; cout << "Please enter integer from 1 to 6: " ; cin >> month ; if ( month = = 1 ) cout << "January" << endl ; if ( month = = 2 ) cout << "February" << endl ; if ( month = = 3 ) cout << "March" << endl ; if ( month = = 4 ) cout << "April" << endl ; if ( month = = 5 ) cout << "May" << endl ; if ( month = = 6 ) cout << "June" << endl ; system("pause") ; return 0 ; OUTPUT Please enter integer from 1 to 6: 5 May 4. In the first example, every one of the conditional statements will be checked even if the user types in the number one (1). In the second example, as soon as a true condition is met and the corresponding statement(s) executed, the program jumps out of the if.. statement. Therefore, the if.. statement is more efficient. The only time it is not more efficient is if it too has to check all the way Page 17
V. Switch Structures down to the last condition. A. A Selection or Branch Structure that does not require the evaluation of a logical expression. 1. Gives the computer the power to choose from among many alternatives. B. Syntax & Use: switch ( expression ) case value 1 : statements 1; break; case value 2 : statements 2 ; break ; : case value n : statements n ; break ; default : statements ; 1. Notice that switch, case, break, and default are all reserved words. 2. The value of the expression ( also called the selector )is usually an identifier ( variable ). The expression or identifier, as well as the values following the case labels, must be of an integral type. Example: integer, character, or boolean value. 3. A particular case should only appear once. 4. One or more statements may follow a case label. 5. How the switch statement executes: i. When the value of the expression is matched against a case value (also called a label ), the statements execute until either a break statement is found or the end of the switch structure is reached. ii. If the value of the expression does not match any of the case values, the statements following the default label execute. If the switch structure has no default label, and if the value of the expression does not match any of the case values, the entire switch statement is skipped. Page 18
iii. A break statement causes an immediate exit from the switch structure. 6. Example Program: #include <iostream> using namespace std; int main ( ) int score ; char grade ; cout << "Please enter the score of the quiz here: " ; cin >> score ; if ( score > 22 ) grade = 'A' ; if ( score > 19 ) grade = 'B' ; if ( score >17 ) grade = 'C' ; if ( score > 14 ) grade = 'D' ; grade = 'F' ; switch ( grade ) case 'A' : cout << "The grade is A. " ; break ; case 'B' : cout << "The grade is B." ; break ; case 'C' : cout << "The grade is C." ; break ; case 'D' : cout << "The grade is D." ; break ; case 'F' : cout << "The grade is F." ; break ; default : cout << "The grade is invalid." ; system("pause") ; return 0; Page 19