C++ Programming: Program Design Including Data Structures, Fourth Edition 5-1
Chapter 5
Control Structures II (Repetition)
At a Glance
Instructor’s Manual Table of Contents
· Overview
· Objectives
· Teaching Tips
· Quick Quizzes
· Class Discussion Topics
· Additional Projects
· Additional Resources
· Key Terms
Lecture NotesOverview
In Chapter 5, students learn how repetition structures are incorporated into programs. Students will explore different types of loops, including count-controlled, sentinel-controlled, flag-controlled, and EOF–controlled loops. The three C++ repetition structures will be introduced: while loops, for loops, and do…while loops. Students will also examine the use of break and continue statements in loops. Finally, they will learn how to incorporate nested repetition and selection structures into their programs.
Objectives
In this chapter, the student will:
· Learn about repetition (looping) control structures
· Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF–controlled repetition structures
· Examine break and continue statements
· Discover how to form and use nested control structures
Teaching Tips
Why is Repetition Needed?
1. Explain why repetition structures are invaluable to a programming language. Discuss why repeating a set of statements in a program using a loop is preferable to typing in the statements over and over.
Teaching
Tip / Students may have felt somewhat limited with previous programming assignments because of the inability to use several sets of input. Discuss how programs from previous chapters, such as the Calculator program (Exercise 9, Chapter 3), could be enhanced with repetition structures.while Looping (Repetition) Structure
1. Explain the syntax of a while structure.
2. Describe the flow of execution in a while loop using Figure 5-1, and define the term infinite loop.
Teaching
Tip / Your students will probably program an infinite loop at some point during this class. Explain how they can stop program execution when running a program in which they have inadvertently programmed an infinite loop (CTRL + C on most systems). Demonstrate with a simple program.3. Discuss the proper use of a loop control variable using Example 5-1.
Designing while Loops
1. Use Example 5-2 to explain that the expression in a while loop typically checks whether a variable(s), called the loop control variable (LCV), satisfies certain conditions.
Case 1: Counter-Controlled while Loops
1. Explain that a counter-controlled loop is useful when you know how many times a set of statements needs to be executed.
2. Describe how to initialize and update the counter variable in a while loop using Example 5-3.
Teaching
Tip / Initializing and incrementing a counter variable can be tricky, especially because they vary slightly among different types of looping structures. As you discuss the loop structures in this chapter, emphasize the steps for implementing an appropriate loop control variable for each of them. For the while loop, note that the counter must be set initially before the loop executes for the first time, and then updated again inside the loop for future executions.Case 2: Sentinel-Controlled while Loops
1. Define the term sentinel and explain how it is used to terminate the execution of a while loop. Use Example 5-4 to illustrate.
Telephone Digits (Example 5-5)
1. Step through the Telephone Digits program to illustrate how a user can be prompted to enter a sentinel that terminates a program.
Case 3: Flag-Controlled while Loops
1. Explain that a flag-controlled while loop uses a bool variable, called a flag variable, to control the loop.
Number Guessing Game (Example 5-6)
1. Step through the Number Guessing Game to demonstrate how a flag variable can be set to true when the user enters the correct response.
Case 4: EOF-Controlled while Loops
1. Explain why the use of an EOF-controlled loop is sometimes preferable to a sentinel-controlled loop.
2. Describe how the variable cin can act as a loop control variable by returning a false value when there is no more input data.
eof Function
1. Introduce the C++ function eof and demonstrate how it is used to determine the end of input data in a file.
Teaching
Tip / Mention that when creating a data file that will be used for a program that relies on the end-of-file marker, it might be wise to include a final newline at the end of the data. Some compilers, such as gcc, require this to properly execute eof.More on Expressions in while Statements
1. Explain that the expression in a while statement may be a complex logical expression that requires more than one condition to be satisfied for loop execution. Discuss possible modifications to the Number Guessing Game to illustrate this concept.
2. Discuss the implementations of the Checking Account Balance and Fibonacci Number programs at the end of this section to consolidate the students’ understanding of the while loop repetition structures.
Quick Quiz 1
1. How do you avoid an infinite loop?
Answer: Verify that the loop’s body contains statement(s) that assure the exit condition will eventually be false
- True or False: The loop control variable for a while loop must be initialized before the while loop.
Answer: True
- The expression in a while loop checks whether a variable, called the ______, satisfies certain conditions.
Answer: loop control variable (LCV)
loop control variable
LCV
- A(n) ______is an arbitrary value that, when read, stops the execution of a loop.
Answer: sentinel
for Looping (Repetition) Structure
1. Explain that the primary purpose of the for loop repetition structure is to simplify the writing of count-controlled loops.
2. Discuss the syntax of a for loop, including its three major components: the initial statement, the loop condition, and the update statement.
3. Illustrate the flow of execution in a for loop using Figure 5-2.
4. Demonstrate the various ways a for loop can be used with Examples 5-7 through 5-13. Then, step through the “Classifying Numbers” Programming Example to illustrate the use of a for loop in a complete program.
Teaching
Tip / Emphasize the difference between a for loop and a while loop regarding the initialization of the loop control variable.Teaching
Tip / Ask your students to discuss situations in which they might want to use a floating-point number with a fractional part for a loop control variable. What are the pitfalls of using real numbers for the index variable in a for loop?do…while Looping (Repetition) Structure
1. Explain the syntax of the do…while loop.
2. Describe the flow of execution in a do…while loop using Figure 5-3.
3. Look at Examples 5-15 and 5-16 to illustrate the use of a do…while loop.
Teaching
Tip / Discuss why you might want a loop to execute once before testing for a condition. For example, a posttest loop is useful when the condition that determines the end of the loop is calculated within the loop statement itself.Divisibility Test by 3 and 9 (Example 5-17)
1. Use Example 5-17 to show how to use a do…while loop to determine whether a positive integer is divisible by 3 and 9.
Choosing the Right Looping Structure
1. Describe the situations in which each type of looping structure is preferable.
break and continue Statements
1. Explain that the break statement can be used in a loop structure to provide a means for immediate exit from the structure (as with the switch structure). Explain why using a break statement may be preferable to using flag variables to exit a loop structure.
2. Introduce the continue statement and explain its use in loop structures. Emphasize that it is different from a break statement in that it skips the remaining statements in the loop and proceeds on with the next iteration of the loop.
Teaching
Tip / Discuss the unpredictable results that might occur from misplacing the continue statement in a while or do…while loop. Emphasize that the loop counter variable is incremented in a for loop regardless of the placement of a continue statement.Quick Quiz 2
- How many times does the initial statement of a for loop execute?
Answer: once
- True or False: A semicolon at the end of a for statement is a semantic error.
Answer: True
- What is the purpose of the third expression of the for statement?
Answer: It updates the index variable.
4. True or False: If the loop condition in a for statement is omitted, it is assumed to be false.
Answer: False
Nested Control Structures
1. This section reviews the control structures introduced in this chapter and in Chapter 4. Review the concept of nested structures and explain that both repetition and selection structures can be nested.
2. Using Examples 5-18 through 5-23, demonstrate how using nested structures can increase the functionality of a program.
Teaching
Tip / Discuss the following question with your students to highlight some of the issues with nested loops:In the nested loops in Examples 5-22 and 5-23, are we guaranteed that the end-of-file will not be reached in the inner loop? Why or why not?
Class Discussion Topics
- Discuss the fact that it is important to test for invalid input for the initial sentinel value when using while loops. How might you modify the code in Examples 5-4 and 5-5 to account for an invalid initial sentinel value? In other words, you would like the condition of the while loop to be tested at least once without input failure, and you would also like to avoid an infinite loop. Would initializing the sentinel variable during its declaration be helpful?
- You can use the repetition structures in this chapter interchangeably for many circumstances. There are a few occasions when one is clearly preferable to another. Review these, give an overview of all of the repetition 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
- Ask your students to write a menu-driven program that calculates the total price for a picnic lunch that the user is purchasing for a group of friends. The user is first asked to enter his or her budget for the lunch. The user has the option of buying apples, cheese, and bread. Set the price per apple, price per pound of cheese, and price per loaf of bread in constant variables. Use a nested repetition/selection structure to ask the user what type of item and how much of each item he or she would like to purchase. Keep a running total of the items purchased inside the loop. Exit the loop if the total has exceeded the user’s budget. In addition, provide a sentinel value that allows the user to exit the purchasing loop at any time.
2. Modify the Telephone Digit program and the Checking Account Balance program in this chapter to allow for enhanced user input and error checking. In the Telephone Digits program, rather than terminating the program based on a sentinel value provided by the user, terminate the program whenever the input is NOT any of the menu choices. Modify the Checking Account Balance program to give the user an opportunity to enter a valid transaction code if an incorrect one was encountered in the input file. Verify that the corresponding transaction amount is correct and then perform the transaction.
Additional Resources
- Loops:
www.cprogramming.com/tutorial/lesson3.html
- The for loop:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/_pluslang_the_c.2b2b_.for_statement.asp
- End-of-File Function:
http://mathbits.com/MathBits/CompSci/Files/End.htm
- Control Flow:
http://en.wikipedia.org/wiki/Control_flow
Key Terms
Ø Counter-controlled while loop: while loop that is used when you know how many items of data are to be read; the loop will continue until the condition designated by the counter is met or evaluates to false
Ø Decision maker: expression in an if statement which determines whether to execute the statement that follows it
Ø Divisor: suppose that m and n are integers and m is nonzero. Then m is called a divisor of n if n = mt for some integer t; that is, when m divides n, the remainder is 0.
Ø End-of-file (EOF)-controlled while loop: while loop that stops when it reaches the end of the input file
Ø Fibonacci number: number in the Fibonacci sequence
Ø Fibonacci sequence: an = an-1 + an-2
Ø Flag variable: Boolean variable used to control the execution of a while loop
Ø Flag-controlled while loop: uses a Boolean variable to control the execution of the loop
Ø for loop (indexed loop): used to simplify the writing of count-controlled loops; consists of an initialization statement, the loop condition, and the update statement
Ø for loop control variable: loop control variable in a for loop
Ø Indexed variable: loop control variable in a for loop
Ø Infinite loop: loop that continues to execute endlessly
Ø Loop control variable (LCV): variable that controls the end of the loop
Ø Nesting: putting one control structure inside another
Ø Posttest loop: loop in which the loop condition is evaluated after executing the body of the loop
Ø Pretest loop: loop in which the loop condition is evaluated before executing the body of the loop
Ø Sentinel: arbitrary value used to stop the execution of a loop
Ø Sentinel-controlled while loop: while loop that uses a sentinel value to end the loop
Ø while loop: a looping structure
