Chapter 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

5.

Introduction to Repetition Using for Loops

The previous chapters of the book described how to write a program using input, processing, and output
statements. So far, the processing in our programs has been strictly sequential, i.e., the steps are
performed one after the other, starting from the first statement. We have also shown how to draw the
logical steps of a program in a flowchart. In this chapter, we will discuss the importance of being able to
repeat a set of statements in a program. This allows one or more statements to be repeatedly executed
until some condition is met. We will show how repetition is drawn in a flowchart and then explain how it
is implemented in a program using a for loop.

5.1 The Need for Repetition

Suppose we have to write a program to produce five lines of output, where each line contains 10 asterisks
(stars):

**********
**********
**********
**********
**********

The following program can be written to produce the required output:

#include <iostream>

using namespace std;

int main () {

cout << "**********" << endl;


cout << "**********" << endl;
cout << "**********" << endl;
cout << "**********" << endl;
cout << "**********" << endl;

return 0;
}

1
Suppose that we require 10 lines of output instead of 5. How can we modify the program to generate the
required output? A simple solution is to insert five more cout statements, similar to the existing five. Now,
suppose that we require 100 lines of output instead of 10. What do we do? We can keep on inserting cout
statements but after a while, you will realize that this is not a very effective approach for producing the
required output.

What we need is a way to tell the computer to execute the following statement 5 times, or 10 times, or
100 times, or indeed, any number of times:

cout << "**********" << endl;

This can be done by means of a repetition statement. In particular, a for loop can be used to tell the
computer to execute a set of instructions a certain number of times until some condition is met.

To use a for loop to display the cout statement above, we must help the computer to keep track of the
number of lines that have already been displayed. This can be done using an integer variable, count. At
any moment in time, the value in count indicates how many lines have already been displayed. At the
beginning of the output, count is given the value zero since no lines have been displayed as yet:

count = 0;

Each time a line is displayed, we add one to the value currently stored in count. In Chapter 3, we showed
how to add one to the value stored in a variable count:

count = count + 1;

Suppose we need to display 10 lines of output. Before displaying a line of output, we check to see if count
is less than 10. If it is, another line of output is displayed and we add one to the value of count; then we
return to the statement which checks to see if count is less than 10. If count is equal to 10, we end the
program. Figure 5.1 is a flowchart which shows the logic of the repetition statement:

2
Start

count = 0

Is No
count < 10?

Yes

output
10 stars
on a line

add 1 to count

End

Figure 5.1: Flowchart for Displaying Multiple Lines of Output

Figure 5.1 contains a “Decision” symbol. The decision that has to be made is to determine if count is less
than 10; it is represented textually as follows, “Is count less than 10?” There are only two outcomes of
this decision: Yes or No (or true or false). If the result is Yes, we would like to display another line of output.
So, a line labelled “Yes” is drawn from the “Decision” symbol to the “Input/Output” symbol which displays
a line of output. If the result is No, we would like to terminate the program. So, a line labelled “No” is
drawn from the “Decision” symbol to the “End” symbol.

As long as count is less than 10, a line of output will be produced and count will be updated by one. Thus,
the logic for producing a line of output and updating the count variable is repeated several times (10 times,

3
to be exact). So, instead of having to write 10 cout statements, we can write the cout statement once
and repeat it 10 times. This is referred to as repetition.

5.2 Repetition with for Loops

The program corresponding to the flowchart of Figure 5.1 is given below. Repetition is achieved by means
of a for loop, a commonly used construct for repeating one or more statements in a program.

#include <iostream>

using namespace std;

int main () {

int count;

for (count = 0; count < 10; count = count + 1)


cout << "**********" << endl;

return 0;
}

The variable count is called a loop control variable since it controls how many times the for loop will be
executed. The for loop consists of three sections separated with a semi-colon within brackets. The first
section gives the loop control variable an initial value:

count = 0;

The second section is the decision that must be made before the loop is repeated. To specify “Is count
less than 10?”, the following expression is used:

count < 10;

This expression will evaluate to either true or false. If it is true, the statement in the “body” of the for loop
will be executed. If it is false, the statement will not be executed and the loop terminates.

4
The third section tells the program how to modify the loop control variable after each execution of the
for loop. In this case, all we want to do is to add one to its value, so we use the following statement:

count = count + 1

The “body” of the loop consists of a single statement which may be repeated several times, depending on
the value of the expression in the second section. The different parts of a for loop are shown in Figure 5.2.

Gives an initial value to the loop


control variable, count

This expression must evaluate to true,


in order for the body of the for loop
to be executed

This statement tells the program how


to update the loop control variable at
the end of the loop
for (count = 0; count < 10; count = count + 1)
Body of the for loop, containing the
cout << "**********" << endl;
cout statement to be repeated

Figure 5.2: Parts of a for Loop

In Figure 5.3, we show the relationship between the steps in the flowchart of Figure 5.1 with the different
parts of the corresponding for loop shown in Figure 5.2. In Figure 5.3, the steps of the flowchart which
may be repeated have been shaded.

When the program is compiled and executed, it generates the following output (10 lines of asterisks):

**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

5
Start

count = 0

Is No
count < 10?

Yes

for (count = 0; count < 10; count = count + 1) output


cout << "**********" << endl; 10 stars
on a line

add 1 to count

End

Figure 5.3: Mapping of Flowchart Steps to Program Statements

5.3 Writing a for Loop with Variables

Suppose we would like the for loop from the previous section to display fifteen lines of output, each with
10 asterisks. A simple approach is to change the 10 in the second section of the for loop to 15:

for (count = 0; count < 15; count = count + 1)


cout << "**********" << endl;

While this approach gets the job done, it is not very effective since we will have to modify the for loop
whenever we need to display a different number of lines. We will now show how to display any amount
of lines without modifying the for loop.

6
The first and third sections of a for loop are assignment statements. An arithmetic expression containing
variables can be written on the right-hand side of an assignment statement. So, if start is an integer
variable containing a value, the first section of the loop could be written as:

count = start;

Similarly, if increment is an integer variable containing a value, the third section of the for loop could be
written as:

count = count + increment

The second section of a for loop is a relational expression (to be discussed in Chapter 10). This, too, can
be formed using one or more variables. For example, suppose numLines is an integer variable containing
the value, 10. The expression,

count < numLines

returns true as long as the value of count is less than the value in numLines, i.e., 10. If the value of numLines
is 15, the expression returns true as long as the value of count is less than the value in numLines. Thus, by
using a variable in the expression, there is no need to change the second section of the for loop to display
a different amount of lines. All that has to change is the value of the variable (e.g., by using an assignment
statement or an input statement, before the for loop is executed).

When a variable is used in the second section of the for loop, the original for loop can be written as follows:

for (count = 0; count < numLines; count = count + 1)


cout << "**********" << endl;

7
5.4 Using a for Loop to Display a Sequence of Numbers

Consider the following for loop:

int count;
for (count = 0; count < 10; count = count + 1)
cout << count << endl;

What does this for loop display? The “body” of the for loop consists of the statement,

cout << count << endl;

This statement displays the value of the count variable on the monitor and then goes to a new line
(because of the endl keyword). The first time through the loop, the value of count is zero, so the for loop
displays a single 0 on a line by itself:

The value in count is updated at the end of the loop to 1 (by the statement, count = count + 1). Since
1 is less than 10, the loop is executed again, and this time the value 1 is displayed on a line by itself since
count has the value 1. The output is now:

0
1

The value in count is updated at the end of the loop to 2. Since 2 is less than 10, the loop is executed again
and the value 2 is displayed on a line by itself. The output is now:

0
1
2

8
This continues until count is 9. The output is now:

0
1
2
3
4
5
6
7
8
9

After displaying the 9, count is updated to 10. Since 10 is not less than 10, the expression evaluates to
false, causing the loop to terminate. This example demonstrates that it is possible to access the value of
the loop control variable at any time inside the for loop. The value can be displayed on the monitor as in
the example above or it can be used in an arithmetic expression. In the next chapter, we will show several
examples where the loop control variable is used in an arithmetic expression.

So, the for loop generates a sequence of numbers starting from 0 and ending at 10. Let us now consider
what happens if we leave out the endl keyword from the cout statement:

cout << count;

As before, the value of count is displayed each time the for loop is executed; however, the values are
joined together in the output as follows (since there is no white space displayed between the values of
count):

0123456789

To generate a different sequence of numbers, say, from 5 to 20, the first and second sections of the for
loop should be modified as follows:

int count;
for (count = 5; count < 20; count = count + 1)
cout << count << endl;

9
It is also possible to change the interval between each number in the sequence by modifying the
arithmetic expression in the third section of the for loop. For example, if we want an interval of 5, the
third section should be written as follows:

count = count + 5;

This causes the following output to be produced:

5
10
15

5.5 Exercises

1. What is the output produced by the following for loop?

int count;
for (count = 5; count < 10; count = count + 1)
cout << "**********" << endl;

2. What is the output produced by the following for loop?

int count;
for (count = 5; count < 15; count = count + 1)
cout << "**********" << endl;

3. What is the output produced by the following for loop?

int count;
for (count = 0; count <= 10; count = count + 1)
cout << count << endl;

4. What is the output produced by the following for loop?

int count;
for (count = 20; count <= 10; count = count + 1)
cout << count << endl;

10
5. What is the output produced by the following for loop?

int count;
for (count = 0; count < 10; count = count + 2)
cout << count << endl;

6. Using a for loop, write a program to display the following figure on the monitor:

----------
| |
| |
| |
| |
| |
----------

11

You might also like