Control Statements part II
Control Statements part II
Chapter
Control Structures II
(Repetition)
Objectives
In this chapter, you 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
Why Is Repetition Needed?
Why Is Repetition Needed?
1 2 3 4 5 6 7 8 9 10
Sentinel-Controlled while Loops
Case 2: Sentinel-Controlled
while Loops
• Sentinel variable is tested in the condition
and loop ends when sentinel is encountered
1 2 3 4 5 6 7 8 9 10
for
Looping (Repetition) Structure
• The general form of the for statement is:
Sum is 110
Examples Using the for Statement
(Cont.)
1 2 3 4
Broke out of loop at count = 5
1 // Name Surname, Date, Time.
2 // continue statement terminating an iteration of a for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
Loop 10 times
7 int main()
8 {
9 for ( int count = 1; count <= 10; count++ ) // loop 10 times
10 {
11 if ( count == 5 ) // if count is 5,
12 continue; // skip remaining code in loop
13
14 cout << count << " ";
Skip line 14 and proceed to
15 } // end for line 9 when count equals 5
16
17 cout << "\nUsed continue to skip printing 5" << endl;
18 return 0; // indicate successful termination
19 } // end main
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
Good Programming Practice
Some programmers feel that break and
continue violate structured programming. The
effects of these statements can be achieved by
structured programming techniques, so these
programmers do not use break and continue.
Most programmers consider the use of break in
switch statements acceptable.
Performance Tip
The break and continue statements,
when used properly, perform faster than do
the corresponding structured techniques.
Software Engineering Observation
• Answer:
*****
****
***
**
*
Summary (continued)
• while: expression is the decision
maker, and the statement is the body
of the loop
• A while loop can be:
− Counter-controlled
− Sentinel-controlled
• In the Windows console environment,
the end-of-file marker is entered using
Ctrl+z
Summary (continued)
• 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