Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.

Similar presentations


Presentation on theme: "CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how."— Presentation transcript:

1 CHAPTER 4 CONTROL STRUCTURES I Selection

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 switch in a program Learn to use the assert function 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. 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.

4

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

6 Relational Operators in Logical Expression ExpressionMeaningValue 8 < 158 is less than 15true 6 != 66 is not equal to 6false ‘R’ > ‘T’ ASCII 82 is greater than 84 false “Hello”>“Hen”string comparison false 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.

7 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.

8

9 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.

10 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 !foundfalse x > 4.0true !numfalse !found && (x >= 0)false !(found && (x >= 0))false x + y <= 20.5true (n >= 0) && (n <= 100)true ('A' <= ch && ch <= 'Z')true (a + 2 <= b) && !flagtrue

11 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

12 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. 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).

13 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.

14 One-way Selection The syntax of one-way selection is: if(expression) statement if(score >= 90) grade = 'A';

15 Two-way Selection Two-way selection takes the form: if(expression) statement1 else statement2 if ( x>=0 ) cout << “Positive number”; else cout << “Negative number”;

16 Compound (Block of) Statement A compound statement (also called a block of statements) takes the form { statement1; statement2;. statementn; }  A compound statement is considered a single statement.

17 Thus, instead of a simple two-way selection as represented by if(age > 18) cout<<"Eligible to vote."<<endl; else cout<<"Not eligible to vote."<<endl; we may substitute the compound statements: if(age > 18) { cout<<" Eligible to vote."<<endl; cout<<" No longer a minor."<<endl; } else { cout<<"Not eligible to vote."<<endl; cout<<"Still a minor."<<endl;

18 Multiple Selections: Nested if There is a way of considering multiple selections using if...else, if we permit the action statement itself to be an if... statement. When one control statement is within another, it is said to be nested. Consider the following statement. (Assume that all variables are properly declared.)

19 if(score >= 90) cout<<"The grade is A"<<endl; else if(score >= 80) cout<<"The grade is B"<<endl; else if(score >= 70) cout<<"The grade is C"<<endl; else if(score >= 60) cout<<"The grade is D"<<endl; else cout<<"The grade is F"<<endl; Pairing an else with an if : In a nested if statement, C++ associates an else with the most recent incomplete if —that is, the most recent if that has not been paired with an else

20 if(temperature >= 50) if(temperature >= 80) cout<<"Good day for swimming."<<endl; else cout<<"Good day for golfing."<<endl; else cout<<"Good day to play tennis."<<endl; if(temperature >= 70) //Line 1 if(temperature >= 80)//Line 2 cout<<"Good day for swimming."<<endl;//Line 3 else//Line 4 cout<<"Good day for golfing."<<endl; //Line 5 if(GPA >= 2.0) if(GPA >= 3.9) cout<<"Dean\’s Honor List."<<endl; else cout<<"Current GPA below graduation requirement. " <<"\nSee your academic advisor."<<endl;

21 if(cin) cout<<"Input is OK."<<endl; will print Input is OK. if the last input from the standard input device succeeded. If infile is an ifstream variable, then the statement if(!infile) cout<<"Input failed."<<endl; will print Input failed. if the last input associated with the stream variable infile failed.

22 Confusion Between the Equality Operator ( == ) and the Assignment Operator ( = )  C++ allows any expression that can be evaluated to either true or false to be used as an expression in the if statement. Consider the statement if(x = 5) cout<<"The value is five."<<endl; The expression x = 5 is called an assignment expression First, the right side of the operator = is evaluated to 5. The value 5 is then assigned to x. The value 5 also becomes the value of the expression in the if statement. Because 5 is nonzero, the expression in the if statement evaluates to true, so the statement part of the if statement outputs: The value is five.

23 The Conditional Operator (? :) In C++, ?: is called the conditional operator. It is a ternary operator, that is, it takes three arguments. The syntax of using the conditional operator is: expression1 ? expression2 : expression3 This is called a conditional expression.  The conditional expression evaluates as follows: If expression1 evaluates to a nonzero integer (that is, true ), then the result of the conditional expression is expression2, otherwise the result of the conditional expression is expression3. if (a >= b) max = a; else max = b; max = (a >= b) ? a : b;

24 switch STRUCTURES The general form (syntax) of a switch statement is: switch(expression) { case value1: statements1; break; case value2: statements2; break;. case valuen: statementsn; break; default: statements; }

25

26 #include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “ grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; switch( toupper(FeedGrade) ) { case 'A': cout << "30 cents per pound.\n"; break; case 'B': cout << "20 cents per pound.\n"; break; case 'C': cout << "15 cents per pound.\n"; break; default: cout << "That is an invalid”<< “choice.\n"; } #include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; if ( toupper(FeedGrade) == ‘A’ ) cout << "30 cents per pound.\n"; else if ( touuper(FeedGrade) == ‘B’ ) cout << "20 cents per pound.\n"; else if ( toupper(FeedGrade) == ‘C’) cout << "15 cents per pound.\n"; else cout << "That is an invalid”<< “choice.\n"; }

27 #include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “ grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; switch(FeedGrade) { case 'a': case 'A': cout << "30 cents per pound.\n"; break; case 'b': case 'B': cout << "20 cents per pound.\n"; break; case 'c': case 'C': cout << "15 cents per pound.\n"; break; default: cout << "That is an invalid”<< “choice.\n"; } #include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; if (FeedGrade==‘a’ || FeedGrade == ‘A’) cout << "30 cents per pound.\n"; else if (FeedGrade==‘b’ || FeedGrade == ‘B’) cout << "20 cents per pound.\n"; else if (FeedGrade==‘c’ || FeedGrade == ‘C’) cout << "15 cents per pound.\n"; else cout << "That is an invalid”<< “choice.\n"; }

28 TERMINATING A PROGRAM WITH THE assert FUNCTION Certain types of errors that are very difficult to catch can occur in a program. For example, division by zero can be difficult to catch using any of the programming techniques you have examined so far. C++ includes a predefined function, assert, that is useful in stopping program execution when certain elusive errors occur.

29 int numerator; int denominator; int quotient; double hours; double rate; double wages; char ch; 1. quotient = numerator / denominator; 2. if(hours > 0 && ( 0 < rate && rate <= 15.50)) wages = rate * hours; 3. if('A' <= ch && ch <= 'B')

30 The syntax to use the assert function is assert(expression); Here expression is any logical expression. If expression evaluates to true, the next statement executes. If the expression evaluates to false, the program terminates and indicates where in the program the error occurred. The specification of the assert function is found in the header file cassert. Therefore, for a program to use the assert function, it must include the following statement: #include

31 assert(denominator); quotient = numerator / denominator; If denominator is 0, the assert statement halts the execution of the program with an error message similar to the following: Assertion failed: denominator, file c:\temp\assert function\assertfunction.cpp, line 20

32 During program development and testing, the assert statement is very useful for enforcing programming constraints. Although assert statements are useful during program development, after a program has been developed and put into use, if an assert statement fails for some reason, an end user would have no idea what the error means. After you have developed and tested a program, you should remove or disable assert statements. In a very large program, it could be tedious, and perhaps impossible, to remove all of the assert statements. If you plan to modify a program in the future, you might like to keep the assert statements.

33 You can disable assert statements by using the following preprocessor directive: #define NDEBUG This preprocessor directive #define NDEBUG must be placed before the directive #include.


Download ppt "CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how."

Similar presentations


Ads by Google