C++ Programming: From Problem Analysis To Program Design, Fifth Edition
C++ Programming: From Problem Analysis To Program Design, Fifth Edition
Objectives
In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countcontrolled, sentinel-controlled, flagcontrolled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures
C++ Programming: From Problem Analysis to Program Design, Fifth Edition
2
Objectives (cont'd.)
Learn how to avoid bugs by avoiding patches Learn how to debug loops
10
11
12
13
14
eof Function
The function eof can determine the end of file status eof is a member of data type istream
Like other I/O functions
The syntax for the function eof is: where istreamVar is an input stream variable, such as cin
C++ Programming: From Problem Analysis to Program Design, Fifth Edition
15
16
Given the first two numbers of the sequence (say, a1 and a2)
nth number an, n >= 3, of this sequence is given by: an = an-1 + an-2
17
18
19
20
21
22
23
26
27
28
30
31
33
35
36
37
38
After the break statement executes, the program continues with the first statement after the structure
C++ Programming: From Problem Analysis to Program Design, Fifth Edition
40
(cont'd.)
continue is used in while, for, and dowhile structures
When executed in a loop
It skips remaining statements and proceeds with the next iteration of the loop
41
Answer:
***** **** *** ** *
43
Some programmers address the symptom of the problem by adding a software patch Should instead resolve underlying issue
44
Debugging Loops
Loops are harder to debug than sequence and selection structures Use loop invariant
Set of statements that remains true each time the loop body is executed
45
Summary
C++ has three looping (repetition) structures:
while, for, and dowhile
while, for, and do are reserved words while and for loops are called pretest loops do...while loop is called a posttest loop while and for may not execute at all, but do...while always executes at least once
C++ Programming: From Problem Analysis to Program Design, Fifth Edition
46
Summary (cont'd.)
while: expression is the decision maker, and the statement is the body of the loop A while loop can be:
Counter-controlled Sentinel-controlled EOF-controlled
In the Windows console environment, the end-of-file marker is entered using Ctrl+z
C++ Programming: From Problem Analysis to Program Design, Fifth Edition
47
Summary (cont'd.)
for loop: simplifies the writing of a counter-controlled while loop
Putting a semicolon at the end of the for loop is a semantic error
Executing a break statement in the body of a loop immediately terminates the loop Executing a continue statement in the body of a loop skips to the next iteration
C++ Programming: From Problem Analysis to Program Design, Fifth Edition
48