Chapter 4

advertisement

C++ Programming: Program Design Including Data Structures, Fourth Edition

Chapter 4

Control Structures I (Selection)

At a Glance

Instructor’s Manual Table of Contents

Overview

Objectives

Teaching Tips

Quick Quizzes

Class Discussion Topics

Additional Projects

Additional Resources

Key Terms

4-1

C++ Programming: Program Design Including Data Structures, Fourth Edition

Lecture Notes

4-2

Overview

Thus far, your students have only written programs that execute statements in sequential order, from beginning to end. Beginning in this chapter, students will learn how to write code that executes based on certain conditions. Two major categories of control structures will be discussed in this text: selection structures are introduced in this chapter, and repetition structures in the next. In the process of learning about control structures, students will also become familiar with relational operators and Boolean expressions. Finally, they will learn how to handle input errors with the assert function.

Objectives

In this chapter, the student 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 how to use the assert function to terminate a program

Teaching Tips

Control Structures

1.

Discuss the three ways in which a computer processes a program: in sequence, selectively, and repetitively. Use Figure 4-1 to illustrate program flow in these three situations.

2.

Introduce the concept of conditional statements with examples from page 169.

Teaching

Tip

Your students may have felt that the programs in the previous chapters were rather pointless in terms of functionality. Once students are introduced to conditional statements, they will begin to see the power of programming. Revisit some of the programs in previous chapters, such as the Movie Ticket Sale program, and discuss how they might be enhanced with conditional statements.

C++ Programming: Program Design Including Data Structures, Fourth Edition 4-3

Relational Operators

1.

Discuss how conditions are evaluated by comparisons, either for equality or inequality.

Use examples from this section to illustrate.

2.

Explain that conditions are represented in C++ by Boolean expressions. Define the terms logical (Boolean) expression and logical (Boolean) values.

3.

Using Table 4-1, go over the six C++ relational operators.

Teaching

Tip

Students are most likely familiar with Boolean logic; however, you might give a brief review of truth tables to enhance the discussion of selection structures.

Here is one Web site with a simple introduction: www.learn-c.com/boolean.htm

.

Relational Operators and Simple Data Types

1.

Explain that relational operators may be used with all three simple data types, but the behavior of the expression is dependent on the type of data.

Comparing Floating-Point Numbers for Equality

1.

Use Example 4-1 to illustrate the unpredictability of comparing floating-point numbers for equality.

Comparing Characters

1.

Using Table 4-2, demonstrate how relational expressions with ASCII characters are evaluated.

2.

Review how C++ returns the result of logical expressions with the integers 0 or 1.

Relational Operators and the string Type

1.

Explain that variables of type string are compared character by character in sequence. Step through a few of the string expressions in Table 4-3 and Table 4-4 to illustrate how strings are compared in varying circumstances.

Teaching

Tip

Emphasize OOP concepts by mentioning that the string comparison operators are actually overloaded to compare string objects. Discuss how the equality operator might be implemented.

C++ Programming: Program Design Including Data Structures, Fourth Edition 4-4

Quick Quiz 1

1.

Name all the possible values of Boolean variables.

Answer: true and false , or 0 and 1

2.

True or False: In C++, true and false are reserved words.

Answer: True

3.

A(n) ____________________ operator allows you to make comparisons in a program .

Answer: relational

4.

The ____________________ operator in C++ is == .

Answer: equality

Logical (Boolean) Operators and Logical Expressions

1.

Explain how to form and evaluate logical expressions that are combinations of other logical expressions. Use Table 4-5 to define the three C++ logical operators.

Order of Precedence

1.

Discuss the order of precedence of the relational and logical operators using Table 4-9.

Step through some of the more complex expressions in Example 4-5 to illustrate these rules.

2.

Step through the truth tables (Tables 4-6 through 4-8) for the !

, & , and || operators.

Use Examples 4-2 through 4-4 to illustrate.

Teaching

Tip

Students may need a little practice evaluating complex logical expressions.

Write the expression in Example 4-7 on the board and give the class a few minutes to evaluate the result.

Short-Circuit Evaluation

1.

Introduce short-circuit evaluation and explain that C++ uses this type of evaluation for logical expressions. int Data Type and Logical (Boolean) Expressions

1.

Describe how the int data type is used in C++ to manipulate Boolean expressions.

Mention that this data type was used for all logical expressions before the introduction of the bool type in more recent C++ versions.

C++ Programming: Program Design Including Data Structures, Fourth Edition bool Data Type and Logical (Boolean) Expressions

4-5

1.

Explain how the bool data type is used in C++ to manipulate Boolean expressions.

Selection: if and if…else

1.

The remainder of the chapter discusses two selection, or branch, structures that are used to incorporate decision making into a program: if statements and the switch structure. Briefly describe how they are used to alter program flow before introducing the if statement.

One-Way Selection

1.

Explain the syntax of the if statement, which is the one-way selection structure in

C++. Illustrate how this statement executes using the flowchart in Figure 4-2.

2.

Use Examples 4-9 through 4-12 to emphasize the correct syntax for the if statement and common coding errors that can result in incorrect results.

Two-Way Selection

1.

Discuss how C++ provides two-way selection through the if…else statement. Explain the syntax of this statement.

2.

Use Examples 4-13 through 4-17 to point out common coding errors when using multiple selection statements.

Compound (Block of) Statements

1.

Discuss the use of compound, or block, statements to allow the execution of more than one statement after a branching decision has evaluated to true . Explain the use of curly braces for multiple statements.

Teaching

Tip

Emphasize that curly braces are used for any type of block statements in C++, not just selection structures. As an example, remind your students that the body of the function main is also enclosed in curly braces, as are all functions.

Multiple Selections: Nested if

1.

Define a nested if statement as a selection structure in which one control statement is located within another.

C++ Programming: Program Design Including Data Structures, Fourth Edition

2.

Discuss how to correctly pair an else with an if . Step through some nested if examples (4-18 though 4-23) to demonstrate the results of incorrectly paired if …

4-6 else statements.

Teaching

Tip

Discuss the conventions regarding indentation for multiple selection statements.

Mention that although the computer does not take indentation into account when evaluating expressions, the code is much more readable and less prone to errors when indented properly.

Comparing if…else Statements with a Series of if Statements

1.

Compare the two if structures in this section and explain when one is preferable to the other.

Using Pseudocode to Develop, Test, and Debug a Program

1.

Define the term pseudocode and explain its usefulness in program development.

Emphasize that a walk-through of your pseudocode with test data can uncover both syntactic and semantic errors.

Teaching

Tip

Mention that as students code more complex expressions, they will probably encounter more errors while compiling. Assure them that this is a normal process. Encourage them to write code in smaller segments and compile at regular intervals for easier debugging.

Input Failure and the if Statement

1.

Describe how to stop program execution with an if statement when input failure occurs. Mention some common causes of input failure and how to indicate these to the user.

2.

Step through the program in this section to illustrate program termination code.

Confusion Between the Equality Operator ( == ) and the Assignment Operator ( = )

1.

Emphasize that inadvertently using an assignment operator instead of an equality operator is an error that can cause serious problems in a program. Demonstrate with some examples from this section.

Conditional Operator ( ?: )

1.

Describe how the conditional operator is used to make branching code more concise.

C++ Programming: Program Design Including Data Structures, Fourth Edition 4-7

Quick Quiz 2

1.

The conditional expression portion of an if statement is sometimes called a(n)

____________________ because it decides whether to execute the statement that follows it.

Answer: decision maker

2.

What is an action statement?

Answer: An action statement is the statement following the conditional expression in an if statement.

3.

True or False: The if…else statement is a one-way selection structure.

Answer: False

4.

A(n) ____________________ operator takes three operands.

Answer: ternary

switch Structures

1.

Introduce the switch structure and describe its syntax in detail. Explain that the switch structure allows the computer to choose among several alternatives.

2.

Explain how a switch structure works using the flowchart in Figure 4-4.

3.

Step through Examples 4-24 through 4-26 to demonstrate the use of the switch structure.

4.

Discuss when to use a switch statement instead of an if…else statement.

Terminating a Program with the assert Function

1.

Explain that the C++ predefined function, assert , is useful in stopping program execution when certain errors occur. Describe these types of errors using the code in this section.

2.

Note the syntax for the assert function as well the header file in which it is included.

3.

Explain how to disable assert functions in a program and discuss the reasons for doing this.

4.

Step through the Cable Company Billing program at the end of the chapter. Encourage students to compile and execute this program.

C++ Programming: Program Design Including Data Structures, Fourth Edition 4-8

Class Discussion Topics

1.

What are the advantages and disadvantages to using the int data type rather than the bool data type to manipulate Boolean expressions? Why do students think the int data type is still used for Boolean expressions?

2.

You can use the selection structures in this chapter interchangeably for many circumstances. There are a few occasions when one is clearly preferable to another based on input data. Some of these situations were touched on in the switch statement discussion. Review these, give an overview of all of the selection structures discussed in the chapter, and then discuss how to determine which structure to use when there is no clear indication. How much of the choice should be based on personal preference and how much on conventional practices? Are there performance issues as well?

Additional Projects

1.

Students have most likely encountered input failure or abnormal program termination when attempting to run programming examples from previous chapters. Ask students to choose two programming examples from Chapters 3 or 4 (either from the chapter sections or the final programming examples) and add the appropriate assert statements to them.

2.

Ask students to enhance the “Student Grade” Programming Example in Chapter 3 to output a letter grade for the student after the average has been calculated. The grade should distinguish between A, A+, and A- (and so on) as well. Also, indicate if the student has passed the class (higher than C).

Additional Resources

1.

Boolean Operations: www.cplusplus.com/doc/papers/boolean.html

2.

Control Structures: www.cplusplus.com/doc/tutorial/control.html

3.

Debugging Hints: www.codeguru.com/cpp/tic/tic0045.shtml

4.

The Use of Braces in C/C++: http://cplus.about.com/od/cprogrammingtip1/l/aa010102a.htm

C++ Programming: Program Design Including Data Structures, Fourth Edition 4-9

Key Terms

Action statement : statement following the expression in an if statement

Associativity : the order in which operators are grouped and evaluated

Compound statement (block of statements) : consists of a sequence of statements enclosed in curly braces, { and }

Conditional expression : expression that uses a conditional operator

Conditional operator : ternary operator written as “?:”; the three arguments explain what the condition is, what the result will be if the condition is true , and what the result will be if the condition is false

Decision maker : expression in an if statement which determines whether to execute the statement that follows it

Logical (Boolean) expression : expression that has a value of either true or false

Logical (Boolean) operators : enable you to combine logical expressions

Logical (Boolean) values : true and false

Nested : when one control statement is located within another

Pairing an else with an if : rule in which an else statement is associated with the most recent incomplete if statement

Pseudocode (pseudo) : informal mixture of C++ and ordinary language used to design an outline of a logical solution to a problem

Relational operator : used to make comparisons in a program

 Selector : expression used in a switch statement that determines which case will be executed

Short-circuit evaluation : 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

Switch structure : selection structure that does not require the evaluation of a logical expression

Ternary operator : operator that takes three arguments

Download