Unit 6 Iteration Statements
Unit 6 Iteration Statements
Iteration Statements
Unit 6
INTRODUCTION
In the previous chapter we had seen the concept of control structure which involves making decision having a condition.
If the condition is satisfied then the decision is to execute a particular set of instructions, if not then another set of
instructions.
This unit is dedicated to looping or iteration. It is used when a set of instructions is to be executed multiple times or for
a fixed number of times until a particular condition is satisfied.
LEARNING OBJECTIVES
TOPICS
Loops
• repeat a statement a certain number of times, or while a condition is fulfilled. They are
introduced by the keywords while, do, and for.
while (expression/condition)
{
statement(s)
}
The while-loop simply repeats statement while expression/condition is true. If, after any
execution of statement, expression/condition is no longer true, the loop ends, and the
program continues right after the loop.
Figure 6.1a shows the while loop flowchart. The part of the loop that contains the statements to be
repeated is called the loop body. A one-time execution of a loop body is referred to as an iteration (or
repetition) of the loop. Each loop contains a expression/condition, a Boolean expression that
controls the execution of the body. It is evaluated each time to determine if the loop body is executed. If
its evaluation is true, the loop body is executed; if its evaluation is false, the entire loop terminates and
the program control turns to the statement that follows the while loop.
The loop for displaying Welcome to C++! 100 times introduced in the preceding section is an example of
a while loop. Its flowchart is shown in Figure 6.1b. The expression/condition is count < 100 and the loop
body contains the following two statements:
count = 0;
expression/ false
condition false
(count < 100)?
true
true
statement(s)
(loop body)
cout<< “Welcome to
C++\n”;
count++
(6.1a) (6.1b)
Figure 6.1 The while loop repeatedly executes the statements in the loop body when the expression/condition
evaluates to true.
Note
The expression/condition must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body
contains one statement or none.
10, 9, 8, 7, 5, 4, 3, 2, 1, stop!
The first statement in main sets n to a value of 10. This is the first number in the countdown. Then the
while-loop begins: if this value fulfills the condition n>0 (that n is greater than zero), then the block that
follows the condition is executed, and repeated for as long as the condition ( n>0) remains being true.
The whole process of the previous program can be interpreted according to the following script
(beginning in main):
1. n is assigned a value
2. The while condition is checked (n>0). At this point there are two possibilities:
o condition is true: the statement is executed (to step 3)
o condition is false: ignore statement and continue after it (to step 5)
3. Execute statement:
cout << n << ", ";
--n;
(prints the value of n and decreases n by 1)
4. End of block. Return automatically to step 2.
• A thing to consider with while-loops is that the loop should end at some point, and thus the
statement shall alter values checked in the condition in some way, so as to force it to become
false at some point.
• Otherwise, the loop will continue looping forever.
• In this case, the loop includes --n, that decreases the value of the variable that is being evaluated
in the condition (n) by one - this will eventually make the condition ( n>0) false after a certain
number of loop iterations.
• To be more specific, after 10 iterations, n becomes 0, making the condition no longer true, and
ending the while-loop.
do {
statement(s)
} while (condition)
• It behaves like a while-loop, except that condition is evaluated after the execution
of statement instead of before, guaranteeing at least one execution of statement, even
if condition is never fulfilled.
• The do-while loop is usually preferred over a while-loop when the statement needs to be
executed at least once, such as when the condition that is checked to end of the loop is
determined within the loop statement itself.
statement(s)
(loop body)
Figure 6.2 The do-while loop executes the loop body first, then checks
true
Expression/ the expression/condition to determine whether to continue or terminate
condition the loop.
false
What would happen if sum and data were not initialized to 0? Would it cause a syntax error? No. It would cause a
logic error, because sum and data could be initialized to any value.
Tip
Use the do-while loop if you have statements inside the loop that must be executed at least once, as in the case of the do-while loop
in the preceding TestDoWhile Program 8.4. These statements must appear before the loop as well as inside it if you use a while loop.
The for loop is designed to iterate a number of times. Its syntax is:
• Like the while-loop, this loop repeats statement while condition is true.
• But, in addition, the for loop provides specific locations to contain an initialization and
an increase/decrease expression, executed before the loop begins the first time, and after
each iteration, respectively.
• Therefore, it is especially useful to use counter variables as condition.
1. initialization is executed. Generally, this declares a counter variable, and sets it to some
initial value. This is executed a single time, at the beginning of the loop.
2. condition is checked. If it is true, the loop continues; otherwise, the loop ends,
and statement is skipped, going directly to step 5.
3. statement is executed. As usual, it can be either a single statement or a block enclosed in curly
braces { }.
4. increase/decrease is executed, and the loop gets back to step 2.
5. the loop ends: execution continues by the next statement after it.
initialization i = 100
true tru
statement(s) e ”Welcome to
cout<<
(loop body) C++\n”;
Increase/decrease i++
Figure 6.3. A for loop performs an initial action once, then repeatedly executes the statements in the
loop body, and performs an action after an iteration when the expression/condition evaluates to true.
A for loop generally uses a variable to control how many times the loop body is executed and when the
loop terminates. This is called a control variable. The initialization often initializes a control variable, the
increase/decrease usually increments or decrements the control variable, and the expression/condition
tests whether the control variable has reached a termination value. For example, the following for loop
displays Welcome to C++! 100 times:
int i;
for (i = 0; i < 100; i++)
{
cout << "Welcome to C++!\n";
}
The loop control variable can be declared and initialized in the for loop. Here is an example:
If there is only one statement in the loop body, as in this example, the braces can be omitted as shown below:
Tip
The control variable must be declared inside the control structure of the loop or before the loop. If the loop control
variable is used only in the loop, and not elsewhere, it is good programming practice to declare it in the initial-action of
the for loop. If the variable is declared inside the loop control structure, it cannot be referenced outside the loop. In the
preceding code, for example, you cannot reference i outside the for loop, because it is declared inside the for loop.
Note
The initialization in a for loop can be a list of zero or more comma-separated variable declaration statements or assignment
expressions. For example:
The increase/decrease in a for loop can be a list of zero or more comma-separated statements. For example:
This example is correct, but it is a bad example, because it makes the code difficult to read. Normally, you declare and initialize a
control variable as an initial action and increment or decrement the control variable as an action after each iteration.
Note
If the expression/condition in a for loop is omitted, it is implicitly true. Thus, the statement given below in (a), which is an infinite
loop, is the same as in (b). To avoid confusion, though, it is better to use the equivalent loop in (c).
Sometimes there may be situations when you require the control to exit the loop or skip the particular iteration and go
to the next. This can be done using the keyword continue.
A continue statement causes the rest of the body of the loop to be omitted, for the current iteration. The control is
transferred to the code that evaluates the normal test condition for loop termination.
The continue statement is similar to the break statement but instead of terminating the loop, it transfers execution to
the next iteration of the loop. It continues the loop after skipping the remaining statements in its current iteration.
while(condition)
do{
{
statements;
statements;
if(condition)
if(condition)
continue;
continue;
statements;
statements;
}while(condition;
}
statements;
statements;
Example program shows the use of continue to print the following pattern.
Note
The continue statement is always inside a loop. In the while and do-while loops, the loop-continuation-condition is
evaluated immediately after the continue statement. In the for loop, the action-after-each-iteration is performed, then
the loop-continuation-condition is evaluated, immediately after the continue statement.