C++ Repeat Structure
C++ Repeat Structure
Reference:
D.S. Malik. (2009). C++ Programming: From Problem Analysis to Program Design. 4th
Ed.. Course Technology, Cengage Learning. Boston, USA.
Sem 1 Session 1011 1
OBJECTIVES
In this chapter you will learn:
1. about repetition (looping) control structures.
2. how to construct and use counter-controlled, sentinel-
controlled, and flag-controlled repetition structures.
3. How to examine break and continue statements.
1
OUTLINE
1. Repetition structures.
2. while looping (repetition) structures.
3. Designing while loops.
4. for looping (repetition) structures.
5. do…while looping (repetition) structures.
6. break statement.
7. continue statement.
1. Repetition Structures
Assume that a program needs to add five (5)
numbers to find the average.
2
1. Repetition Structures
3
Consider the following C++ program segment:
i=0; i=0; i=0;
while (i<=20) while (i<=20) while (i<=20);
{ { {
cout << i << “ ”; i += 5; cout << i << “ ”;
i += 5; cout << i << “ ”; i += 5;
} } }
cout << endl; cout << endl; cout << endl;
---------------------------------------------------------------Sample Run
0 5 10 15 20 0 5 10 15 20 25
4
3. Counter-Controlled while loops
Know how many times certain statements need to
be executed.
5
3. Sentinel-Controlled while loops
Do not know how many times certain
statements need to be executed, but know
the last entry.
6
3. Flag-Controlled while loops
7
4. for Looping Structure
Initial
statement
Loop true
statement
condition
Update
false
statement
A Flow of
execution of a
for loop
Sem 1 Session 1011 16
8
4. for Looping Structure (cont’)
-----------------Sample Run-----------
for (i=0;i<=20; ii += 5
5)
0 5 10 15 20
cout << i << “ ”;
cout << endl;
9
5. do…while Looping Structure (cont’)
A
statement
true
expression
false
A Flow of
execution of a
do…while loop
Sem 1 Session 1011 19
i=0; i=25;
do do
{ {
cout << i << “ ”; cout << i << “ ”;
i += 5; i += 5;
} while (i<=20); } while (i<=20);
cout << endl; cout << endl;
---------------------------------------------------------------Sample Run
0 5 10 15 20 25
10
6. break statement
11
sum=0;
6. break statement (cont’)
isNegative=false;
7. continue statement
12
7. continue statement (cont’)
13
sum=0;
14