Week# 9
Control Structure – Repetition
Dr Taimur Ahmed
Department of IT & CS, PAF-IAST
Lecture# 20
do-while loop
do-while Loop
❑ General format of do-while loop
do
{
statement 1;
statement 2;
}
while (expression);
Lecture# 20 - do-while Loop | 3
do-while Loop
do
{
statement 1;
statement 2;
}
while (expression);
❑ do-while is a post-test loop – executes the body and then test the
expression
❑ Note that a semicolon is required after (expression)
Lecture# 20 - do-while Loop | 4
do-while Loop – Flowchart
Lecture# 20 - do-while Loop | 5
do-while Loop – Example
int x = 1;
do
{
cout << x << endl;
}
while(x < 0);
❑ Although the test expression is false, this loop will execute one time
because do-while loop is a post-test loop.
Lecture# 20 - do-while Loop | 6
do-while Loop
❑ Loop always executes at least once
❑ Execution continues as long as expression is true, stops repetition
when expression becomes false
❑ Useful in menu-driven programs to bring user back to menu to make
another choice
Lecture# 20 - do-while Loop | 7
do-while Loop – Example 1
Lecture# 20 - do-while Loop | 8
Sentinels
Sentinels
❑ Sentinel: value in a list of values that indicates end of data
❑ Special value that cannot be confused with a valid value, e.g., -999 for
a test score
❑ Used to terminate input when user may not know how many values will
be entered
Lecture# 20 - do-while Loop | 10
Sentinels – Example 2
Lecture# 20 - do-while Loop | 11
Which loop to use?
Which loop to use???
❑ The while loop is a conditional pre-test loop
➢ Iterates as long as a certain condition exits
➢ Validating input
➢ Reading lists of data terminated by a sentinel
❑ The do-while loop is a conditional post-test loop
➢ Always iterates at least once
➢ Repeating a menu
❑ The for loop is a pre-test loop
➢ Built-in expressions for initializing, testing, and updating
➢ Situations where the exact number of iterations is known
Lecture# 20 - do-while Loop | 13