CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures...

33
CHAPTER 4 CONTROL STRUCTURES I Selection

Transcript of CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures...

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

CHAPTER 4

CONTROL STRUCTURES I

Selection

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

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

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

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.

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

RELATIONAL OPERATORS

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

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

Relational Operators in Logical Expression

Expression Meaning Value8 < 15 8 is less than 15 true

6 != 6 6 is not equal to 6 false

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

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

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.

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

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.

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

Example 4-4bool 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';

Expression Value!found falsex > 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

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

Example 4-6Evaluate 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

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

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

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

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.

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

One-way SelectionThe syntax of one-way selection is:

if(expression)

statement

if(score >= 90)grade = 'A';

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

Two-way SelectionTwo-way selection takes the form:

if(expression)

statement1

else

statement2

if ( x>=0 )

cout << “Positive number”;

else

cout << “Negative number”;

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

Compound (Block of) StatementA compound statement (also called a block of statements) takes the form

{

statement1;

statement2;

.

.

.

statementn;

}

A compound statement is considered a single statement.

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

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;

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

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

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

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

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

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;

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

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.

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

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.

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

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;

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

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;}

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

 #include <iostream.h>#include <ctype.h> 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 <iostream.h>#include <ctype.h>

 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";

}

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

 #include <iostream.h> 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 <iostream.h>

 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";

}

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

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.

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

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')

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

• 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 <cassert>

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

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

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

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

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

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