1 / 134

CHAPTER 4 CONTROL STRUCTURES I Selection

CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions

audi
Télécharger la présentation

CHAPTER 4 CONTROL STRUCTURES I Selection

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 4CONTROL STRUCTURES ISelection

  2. In this chapter, you will: • Learn about control structures • Examine relational and logical operators • Explore how to form and evaluate logical (Boolean) expressions • Discover how to use the selection control structures if, if...else, and switchin a program • Learn to use the assertfunction to terminate a program

  3. CONTROL STRUCTURES Three ways that a computer can proceed: • In sequence; • Selectively- by making a choice; also called a branch; • Repetitively (or iteratively)- performing a statement over and over; this is called a loop.

  4. Consider the following 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 grater than 70 degree and it is not raining) recommended activity is golfing • These are examples of conditional statements. • Certain statements are to be executed only if certain conditions are met. • A condition is met if it evaluates to true.

  5. In C++, a condition is represented by a logical (Boolean) expression. • An expression that has a value of either true or false is called a logical (Boolean) expression. • true and false are logical (Boolean) values.

  6. RELATIONAL OPERATORS • A relational operator allows you to make comparisons in a program.

  7. Relational Operators and Simple Data Types ExpressionMeaningValue 8 < 158 is less than 15true 6 != 66 is not equal to 6false 2.5 > 5.82.5 is greater than 5.8false 5.9 <= 7.5 5.9 is less than or equal to 7.5true

  8. Equality of real numbers is usually machine dependent. It is quite possible that on a particular machine 6.8 + 3.1 == 2.7 + 7.2 is false

  9. Comparing values of different data types may produce unpredictable results. • For example, • 8 < '5' • should not be done.

  10. Expressions such as 4 < 6 and 'R' > 'T' are examples of logical (Boolean) expressions. • When C++ evaluates a logical expression, it returns an integer value of 1 if the logical expression evaluates to true; it returns an integer value of 0 otherwise. • In C++, any nonzero value is treated as true.

  11. Relational Operators and the string Type • The relational operators can also be applied to variables of the type string. • Variables of the type string are compared character by character, starting with the first character, using the collating sequence. • The character by character comparison continues until either a mismatch is found or the last characters have been compared and are equal.

  12. Suppose we have the following declarations: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; string str5 = "Big";

  13. If two strings of different lengths are compared and the character by character comparison is equal up to the last character of the shorter string, the shorter string compares as less than the larger string. • For example, Expression Value str4 >= "Billy" false str5 <= "Bigger" true

  14. LOGICAL (BOOLEAN) OPERATORS AND LOGICAL EXPRESSIONS • Logical (Boolean) operators enable you to combine logical expressions • In C++, there are three logical (Boolean) operators: • Logical operators take only logical values as operands and yield only logical values as results. • The operator !is unary, so it has only one operand. • The operators &&and ||are binary operators.

  15. When you use the ! operator, !trueis falseand !falseis true. • Putting ! in front of a logical expression reverses the value of that logical expression. Example 4-1 Expression Value Explanation !('A' > 'B') trueBecause 'A' > 'B' is false, !('A' > 'B')is true. !(6 <= 7) falseBecause 6 <= 7 is true, !(6 <= 7) is false.

  16. Example 4-2 Expression Value Explanation (14 >= 5) && ('A' < 'B') trueBecause (14 >= 5) is true, ('A' < 'B') is true, and true && true is true, the expression evaluates to true. (24 >= 35) && ('A' < 'B') falseBecause (24 >= 35) is false, ('A' < 'B') is true, and false && true is false, the expression evaluates to false.

  17. Example 4-3 Expression Value Explanation (14 >= 5) || ('A' > 'B') trueBecause (14 >= 5) is true, ('A' < 'B') is false, and true || false is true, the expression evaluates to true. (24 >= 35) || ('A' > 'B') falseBecause (24 >= 35) is false, ('A' > 'B') is false, and false ||false is false, the expression evaluates to false. ('A' <= 'a') || (7 != 7) trueBecause ('A' <= 'a') is true, (7 != 7) is false, and true ||false is true, the expression evaluates to true.

  18. Order of Precedence Consider the logical expression: 11 > 5 || 6 < 15 && 7 >= 8 • This logical expression will yield different results if || is evaluated first or && is evaluated first. • If || is evaluated first, this logical expression evaluates to 0 (false). • If && is evaluated first, this logical expression evaluates to 1(true).

  19. Precedence of Operators • Because relational and logical operators are evaluated from left to right, the associativity of these operators is said to be from left to right.

  20. Example 4-4 bool found = true; bool flag = false; int num = 1; double x = 5.2; double y = 3.4; int a = 5, b = 8; int n = 20; char ch = 'B'; ExpressionValue !found false x > 4.0 true !num false !found && (x >= 0) false !(found && (x >= 0)) false x + y <= 20.5 true (n >= 0) && (n <= 100) true ('A' <= ch && ch <= 'Z') true (a + 2 <= b) && !flag true

  21. Example 4-5 //Chapter 4: Logical operators #include <iostream> using namespace std; int main() { bool found = true; bool flag = false; int num = 1; double x = 5.2; double y = 3.4; int a = 5, b = 8; int n = 20; char ch = 'B';

  22. cout<<"Line 1: !found evaluates to " <<!found<<endl; //Line 1 cout<<"Line 2: x > 4.0 evaluates to " <<(x > 4.0)<<endl; //Line 2 cout<<"Line 3: !num evaluates to " <<!num<<endl; //Line 3 cout<<"Line 4: !found && (x >= 0) evaluates to " <<(!found && (x >= 0))<<endl; //Line 4 cout<<"Line 5: !(found && (x >= 0)) evaluates to " <<(!(found && (x >= 0)))<<endl; //Line 5 cout<<"Line 6: x + y <= 20.5 evaluates to " <<(x + y <= 20.5)<<endl; //Line 6 cout<<"Line 7: (n >= 0) && (n <= 100) evaluates to " <<((n >= 0) && (n <= 100))<<endl; //Line 7 cout<<"Line 8: ('A' <= ch && ch <= 'Z') evaluates to " <<('A' <= ch && ch <= 'Z')<<endl; //Line 8

  23. cout<<"Line 9: (a + 2 <= b) && !flag evaluates to " <<((a + 2 <= b) && !flag)<<endl; //Line 9 return 0; } Output: Line 1: !found evaluates to 0 Line 2: x > 4.0 evaluates to 1 Line 3: !num evaluates to 0 Line 4: !found && (x >= 0) evaluates to 0 Line 5: !(found && (x >= 0)) evaluates to 0 Line 6: x + y <= 20.5 evaluates to 1 Line 7: (n >= 0) && (n <= 100) evaluates to 1 Line 8: ('A' <= ch && ch <= 'Z') evaluates to 1 Line 9: (a + 2 <= b) && !flag evaluates to 1

  24. You can insert parentheses into an expression to clarify its meaning. The expression 11 > 5 || 6 < 15 && 7 >= 8 is equivalent to 11 > 5 || (6 < 15 && 7 >= 8) This logical expression evaluates to 1 (true).

  25. Example 4-6 Evaluate the following expression: (17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) && !(3 + 3 == 6) (17 < 4*3+5) || (8*2 == 4*4) && !(3+3 == 6) = (17 < 12+5) || (16 == 16) && !(6 == 6) = (17 < 17) || true && !(true) = false || true && false = false || false = false

  26. Short-Circuit Evaluation • Logical expressions in C++ are evaluated using a highly efficient algorithm. 1.(x > y) || (x == 5) 2. (a == b) && (x >= 7) • In the first statement, the two operands of the operator || are the expressions (x > y) and (x == 5). This expression evaluates to true if either the operand (x > y) is true or the operand (x == 5) is true. • With short-circuit evaluation, the computer evaluates the logical expression from left to right. As soon as the value of the entire logical expression is known, the evaluation stops. • In statement 1, if the operand (x > y) evaluates to true, then the entire expression evaluates to true because true || true is true and true || false is true. Therefore, the value of the operand (x == 5) has no bearing on the final outcome.

  27. In statement 2, the two operands of the operator && are (a == b) and (x >= 7) . • If the operand (a == b) evaluates to false, then the entire expression evaluates to false because false && true is false and false && false is false. • Short-circuit evaluation (of a logical expression): A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known.

  28. Example 4-7 Consider the following expressions: 1. 5 >= 3) || ( x = = 5) 2.(2 == 3) && (x >= 7) • In statement 1, because (5 >= 3) is true and the logical operator used in the expression is ||, the expression evaluates to true. The computer does not evaluate (x == 5). • In statement 2, because (2 == 3) is false and the logical operator used in the expression is &&, the expression evaluates to false. The computer does not evaluate (x >= 7).

  29. Logical (Boolean) Assignments • In C++,there are two ways logical (Boolean) expressions can be manipulated or processed. In this section, we describe both of these. The int Data Type and Logical (Boolean) Expressions • Earlier versions of C++ had no built in data type that had logical (or Boolean) values, true and false. • Since logical expressions are evaluated to either 1 or 0, the value of a logical expression is stored in a variable of the type int. That is, logical (Boolean) expressions were manipulated with the help of int data type. • Recall that any nonzero value is treated as true.

  30. Consider the declaration int legalAge; and the assignment statement legalAge = 21; Regarded as a logical value, the value of legalAge assigned by this statement is considered true. • The assignment statement legalAge = (age >= 21); assigns the value 1 to legalAge if the value of age is greater than or equal to 21. The statement assigns the value 0 if the value of age is less than 21.

  31. The bool Data Type and Logical (Boolean) Expressions • Recent versions of C++ contains a built in data type, bool. • The data typebool, that has logical (Boolean) values true and false. • In C++, bool, true, and false are reserved words. • The identifier true has the value 1 and the identifier false has the value 0. Consider the declaration bool legalAge; The statement legalAge = true; sets the value of the variable legalAge to true and the statement legalAge = (age >= 21); assigns the value true to legalAge if the value of age is >= 21

  32. Sometimes logical expressions do not behave as you might expect. • Suppose, for example, that num is an int variable. • Suppose that you want to write a logical expression that evaluates to true if the value of num is between 0 and 10, including 0 and 10, and that evaluates to false otherwise. • The following expression appears to represent a comparison of 0, num, and 10 that will yield the desired result: 0 <= num <= 10 • Although this statement is a legal C++ expression, you will not get the result you might expect.

  33. Suppose that num = 5. Then 0 <= num <= 10 =0 <= 5 <= 10 = (0 <= 5) <= 10 = 1 <= 10 = 1 (true) • Now suppose that num = 20. Then 0 <= num <= 10 =0 <= 20 <= 10 = (0 <= 20) <= 10 = 1 <= 10 = 1 (true) • This answer is incorrect.

  34. The expression 0 <= num <= 10 will always evaluate to true, no matter what num is. Because 0 <= num evaluates to either 0 or 1, and 0 <= 10 is true and 1 <= 10 is true. • The correct way to write this expression in C++ is 0 <= num && num <= 10

  35. Selection: if ... else • In C++, there are two selections, or branch control structures: if statements and the switch structure. • First we discusses how if and if...else statements can be used to create one-way selection, two-way selection, and multiple selections.

  36. One-way Selection The syntax of one-way selection is: if(expression) statement • If the value of the expression istrue, statement is executed; • if the value isfalse, statement is not executed and the computer goes on to the next statement in the program. • The expression in the if statement is sometimes called a decision-maker because it decides whether to execute the statement or not. • The expression is usually a logical expression. • statement is any C++ statement. • InC++, ifis a reserved word.

  37. Example 4-8 if(score >= 90) grade = 'A'; If (score >= 90) is true, the assignment statement is executed; if it is false, then statement following the if structure is executed. For example, if the value of score is 95,the value assigned to the variable grade is A.

  38. Example 4-9 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--> "; //Line 1 cin>>number; //Line 2 if(number < 0) //Line 3 number = -number; //Line 4 cout<<endl<<"The absolute value is " <<number<<endl; //Line 5 return 0; }

  39. Sample Run: The user input is red. Please enter an integer--> -6734 The absolute value is 6734

  40. To put a semicolon after the parentheses following the expression (that is, before the statement) in an if statement in a one-way selection is a semantic error. The if statement, in such a case will operate on the empty statement represented by the semi-colon. Example 4-10 Consider the following statement: if score >= 90 grade = 'A'; This statement illustrates an incorrect version of an if statement. The parentheses around the logical expression are missing, which is a syntax error.

  41. Example 4-11 Consider the following C++ statements: if(score >= 90); //Line 1 grade = 'A'; //Line 2 • This statement represents a one-way selection. • Because there is a semicolon at the end of the expression, the if statement terminates at Line 1, the action of the if statement is null, and the statement at Line 2 is not part of the if statement at Line 1. • The statement at Line 2 executes regardless of how the if statement evaluates.

  42. Two-way Selection Two-way selection takes the form: if(expression) statement1 else statement2 • In a two-way selection if the value of the expression istrue, statement1 is executed. • If the value of the expression isfalse, statement2 isexecuted. • statement1 and statement2 are any C++ statements • In C++,elseis a reserved word.

  43. Example 4-12 if(hours > 40.0) //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2 else//Line 3 wages = hours * rate; //Line 4 • If the value of the variable hours is greater than 40.0, then the wages include overtime payment. • Suppose that hours is 50. The expression in the if statement at Line 1 evaluates to true, so the statement at Line 2 executes. • If hours is 30, or any number less than or equal to 40, the expression in the if statement at Line 1 evaluates to false. The program skips the statement at Line 2 and executes the statement at Line 4.

  44. To put a semicolon after the expression before statement1, in a two-way selection, is an error in syntax. In this case the if statement ends with the semicolon, statement1 is no longer part of the if statement and the else part of the statement is all by itself. Remember there is no else statement in C++. It cannot be separated from the if statement.

  45. Example 4-13 The following statements show an example of a syntax error: if(hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2 else//Line 3 wages = hours * rate; //Line 4 • Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone. • The semicolon at the end of if statement (see Line 1) ends the if statement, so the statement at Line 2 separates the else clause from the if statement. That is, else is all by itself. • Since there is no else statement in C++, this code generates a syntax error.

  46. Example 4-14: //Program: Weekly wages #include <iostream> #include <iomanip> using namespace std; int main () { double wages, rate, hours; cout<<fixed<<showpoint<<setprecision(2); //Line 1 cout<<"Line 2: Enter working hours and rate: "; //Line 2 cin>>hours>>rate; //Line 3 if(hours > 40.0) //Line 4 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 5 else//Line 6 wages = hours * rate; //Line 7

More Related