Chapter (5)
Chapter (5)
Objectives
In this chapter, you will:
Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures
Objectives (contd.)
In this chapter, you will (contd.):
Learn how to avoid bugs by avoiding patches Learn how to debug loops
10
11
12
13
14
15
16
eof Function
The function eof can determine the end of file status eof is a member of data type istream Syntax for the function eof: istreamVar is an input stream variable, such as cin
17
18
Called the Fibonacci sequence 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
19
20
Write a program that determines the nth Fibonacci number, given the first two numbers
21
22
Repeat Step 3 until the nth Fibonacci number is found Output the nth Fibonacci number
23
24
25
27
29
The initial statement, loop condition, and update statement are called for loop control statements
30
31
32
33
34
35
36
To avoid an infinite loop, body must contain a statement that makes the expression false
37
38
39
40
41
After break executes, the program continues with the first statement after the structure
43
44
Answer:
***** **** *** ** *
46
Some programmers address the symptom of the problem by adding a software patch Should instead resolve underlying issue
47
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
48
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
49
Summary (contd.)
while: expression is the decision maker, and 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
50
Summary (contd.)
for loop: simplifies the writing of a countercontrolled 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
51