Вы находитесь на странице: 1из 14

Repetition with For Loops

In the previous lecture, we discussed the importance of being able to repeat a set of statements in a
program. This was accomplished by means of a for loop. In this lecture, we show how the for loop can
be used to solve a number of different problems involving repetition.

5.1 Review of For Loops

In the previous lecture, a for loop which displays 10 lines of output, each containing 10 stars, was
discussed. The different parts of the for loop are repeated in Figure 5.1 for convenience:

Figure 5.1: Parts of a for Loop

Suppose the for loop of Figure 5.1 was written as follows:

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

What will the 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:

1
0

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

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 obtain 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 section, we will show
how to generate a multiplication table by using the loop control variable in an arithmetic expression.

Before concluding this section, consider what happens if we leave out the endl keyword from the cout
statement:

cout << count;

2
As before, the value of count is displayed each time the for loop is executed; however, the values are
joined together in the output, like this: 0123456789.

5.2 Generating a Multiplication Table

Consider the multiplication table for the number 6:

1 x 6 = 6
2 x 6 = 12
3 x 6 = 18
4 x 6 = 24
5 x 6 = 30
6 x 6 = 36
7 x 6 = 42
8 x 6 = 48
9 x 6 = 54
10 x 6 = 60
11 x 6 = 66
12 x 6 = 72

We can use the following for loop to display the numbers from 1 to 12:

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

Note that the expression in the second section, “count < 13”, will return true for all values of count
between 1 and 12, inclusive. Thus, we will get 12 lines of output. If the expression is written, “count <
12”, it will return false when count is 12 so we will only get 11 lines output.

We can insert “ x 6 = “ on each line of output by simply displaying “ x 6 = “ after displaying the
value of count:

for (count = 1; count < 13; count = count + 1)


cout << count << " x 6 = " << endl;

The for loop now generates the following output:

3
1 x 6 =
2 x 6 =
3 x 6 =
4 x 6 =
5 x 6 =
6 x 6 =
7 x 6 =
8 x 6 =
9 x 6 =
10 x 6 =
11 x 6 =
12 x 6 =

We are not yet done. On each line of output, we need to calculate the value of (1 x 6), (2 x 6), (3 x 6) etc.
and display it after the “ = ”. Each time the loop executes, we can obtain the value stored in count. All
we need to do is to multiply the value in count by 6 and store the result in another variable, times6:

times6 = count * 6;

In the output statement, we can display the value of times6, together with the other values:

cout << count << " x 6 = " << times6 << endl;

However, we have a problem. The for loops we have met so far contain only one line of code to be
repeated (referred to as a statement). But, we now require two lines of code (or two statements) in
order to display the multiplication table, one for calculating the value of times6, and the other one for
displaying the output.

This problem can be easily solved by using a compound statement. A compound statement consists of
zero or more lines of code (or statements) enclosed in curly braces, { and }. It can be used anywhere a
single line of code (or statement) is expected. So, the two lines of code required to display the
multiplication table can be combined into a compound statement and written as the body of the for
loop as follows:

for (count = 1; count < 13; count = count + 1) {


times6 = count * 6;
cout << count << " x 6 = " << times6 << endl;
}

The loop generates all the values for count between 1 and 12. The first time through the loop, time6 is
assigned the value (count * 6) which evaluates to (1 * 6) since count has the value 1. Thus, time6 is

4
assigned the value 6. The cout statement then generates the following output, since count has the value
1 and times6 has the value 6:

1 x 6 = 6

Table 5.1 shows the values of count and times6 as well as the output generated in the first four
executions of the loop.

Loop count Variable times6 Variable Output


Number Generated

1 1 x 6 = 6

2 2 x 6 = 12

3 3 x 6 = 18

4 4 x 6 = 24

Table 5.1: First Four Executions of the Loop to Generate a Multiplication Table

So, the program now generates the required output. However, suppose that we need to display the
multiplication table for the number 8 or the number 11. We have another problem. The for loop
contains an arithmetic expression which multiplies the value of the loop control variable (which goes
from 1 to 12) by 6. To multiply the loop control variable by 8 or 11, we will need to modify the
expression. This is not very practical.

It is better to store the number for the multiplication table in a variable such as timesTable. The value
for this variable can be input by the user from the keyboard. The arithmetic expression can now be
written as follows, where times is the variable which stores the result of (count * timesTable):

5
times = count * timesTable;

The complete program to generate the multiplication table for any number is given below:

#include <iostream>

using namespace std;

int main ()
{

int count;
int timesTable;
int times;

cout << "Please enter number to generate multiplication table: ";


cin >> timesTable;

for (count = 1; count < 13; count = count + 1) {


times = count * timesTable;
cout << count << " x " << timesTable << " = " << times << endl;
}

return 0;
}

Note that the cout statement has to be modified to display the value stored in the timesTable variable.

5.3 Generating Table of Squares

Suppose we would like to generate a table of squares for the numbers 1 through 12. The table should
look like the following:

Number Squared
------ -------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144

Now, the for loop from the previous section generates all the numbers from 1 to 12, so we can use a
similar for loop:

6
for (count = 1; count < 13; count = count + 1) {

Each time the body of the for loop is executed, we can obtain the value of the count variable. All we
have to do is to find the square of this variable and store it in a variable called square. We then display
the value of count, followed by the value of square, followed by a new line. The for loop is shown
below:

for (count = 1; count < 13; count = count + 1) {


square = count * count;
cout << count << " " << square << endl;
}

The for loop generates the following output:

1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144

We are almost there. We now have to write cout statements to display the heading of the table:

Number Squared
------ -------

The following cout statements can display the required heading:

cout << "Number Squared" << endl;


cout << "------ -------" << endl;

But, where do we place these cout statements? Do we place them inside the loop? Or, do we place
them outside the loop? If we place the cout statements inside the loop, the heading will be displayed
each time the loop is executed. This is not what we want. So, the heading must be placed before entry
into the loop. The complete program is given below:

7
#include <iostream>

using namespace std;

int main ()
{
int count;
int square;

cout << "Number Squared" << endl;


cout << "------ -------" << endl;

for (count = 1; count < 13; count = count + 1) {


square = count * count;
cout << count << " " << square << endl;
}

return 0;
}

The program produces the following output:

Number Squared
------ -------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144

Even though the table is not formatted exactly as the one given earlier, it will serve our purpose.

5.4 Generating a Temperature Conversion Table

The formula for converting a temperature expressed in Celcius to its equivalent temperature in
Fahrenheit is given below:

o
Fahrenheit = oCelcius * 9/5 + 32

We would like to write a program to generate the following conversion table:

8
Celcius Fahrenheit

------- ----------
0 32
5 41
10 50
15 59
20 68
25 77
30 86
35 95
40 104

Notice that the values of Celcius go from 0 to 40, inclusive, so we can use a for loop to solve the
problem as follows:

for (count = 0; count < 41; ?) {

In all the for loops we have written so far, the value of count was updated by 1 in the third section of
the loop. Thus, we obtained sequences of values such as {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} and {1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12}. However, we now have to generate the sequence of values {0, 5, 10, 15, 20, 25, 30, 35,
40}. How do we go from 0 to 5, and from 5 to 10, etc.? Each value of count is 5 more than the previous
value. So, the third section of the loop should have the assignment statement, count = count + 5:

for (count = 0; count < 41; count = count + 5) {

The calculation within the loop is fairly straightforward; the complete program is given below:

#include <iostream>

using namespace std;

int main ()
{
int count;
int fahrenheit;

cout << "Celcius Fahrenheit" << endl;


cout << "------- ----------" << endl;

for (count = 0; count < 41; count = count + 5) {


fahrenheit = (count * 9) / 5 + 32;
cout << count << " " << fahrenheit << endl;
}

return 0;
}

9
Again, the output generated is not exactly the same as what is required but it will suffice for our
purpose. Now, suppose that we require the conversion table to go from -40o Celcius to 40o Celcius:

Celcius Fahrenheit
------- ----------
-40 -40
-35 -31
-30 -22
-25 -13
-20 -4
-15 5
-10 14
-5 23
0 32
5 41
10 50
15 59
20 68
25 77
30 86
35 95
40 104

How do we modify the program to generate the required table? All that is necessary is to change the
starting value of the loop control variable, count, in the for loop. It is presently set to zero; however, to
generate the new table, it should be set to -40:

for (count = -40; count < 41; count = count + 5) {


fahrenheit = (count * 9) / 5 + 32;
cout << count << " " << fahrenheit << endl;
}

This is the only change that is required. Note that the loop control variable has been called count in all
the examples so far. We have chosen this name for the loop control variable but it can be called
anything you like; for example, it can be called celcius in the program which generates the temperature
conversion table.

5.5 Generating Table of Squares for Any Range

Suppose we would like to generate a table of squares for any range of numbers, for example, from 2 to
9, inclusive or from 10 to 25, inclusive or from 20 to 100, inclusive. How can this be achieved? First of all,
the lower and upper values of the range must be entered by the user at the keyboard. We can use two
integer variables, lower and upper, to store the lower and upper values of the range. Secondly, the first
section of the for loop should assign to count the value of the lower variable since this is the value we

10
would like to start with. Thirdly, the expression in the second section of the for loop should check that
the value of count is less than or equal to the value of the upper variable (so that we don’t go beyond
the value stored in upper). This can be done as follows, using “<=” to compare count with upper instead
of “<”:

count <= upper

The complete program is given below:

#include <iostream>

using namespace std;

int main ()
{
int lower;
int upper;
int count;
int square;

cout << "Please enter the lower and upper limit for table: ";
cin >> lower;
cin >> upper;

cout << "Number Squared" << endl;


cout << "------ -------" << endl;

for (count = lower; count <= upper; count = count + 1) {


square = count * count;
cout << count << " " << square << endl;
}

return 0;
}

Using a similar approach, the program which displays 10 lines of stars to the monitor, can now input the
number of lines to be displayed from the user and store the value in a variable numLines. The for loop
can then be written as follows:

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


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

Thus, the program can display any amount of lines of stars to the monitor.

11
5.6 Displaying Numbers in Descending Order

At the beginning of the lecture, it was shown how the following for loop displays the numbers 0
through 9, each number in a line by itself:

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


cout << count << endl;

Suppose we wanted to display the numbers in descending order as follows:

9
8
7
6
5
4
3
2
1
0

How should the for loop be written? First of all, the initial value of the loop control variable, count,
should be 9, not zero:

count = 9;

Also, after displaying the value of count, the next value to be displayed is 8. This is one less than 9. After
displaying 8, the next value to be displayed is 7. This is one less than 8, and so on. So, the third section of
the for loop should subtract 1 from count, not add 1:

count = count - 1

So, the for loop could be written as follows:

for (count = 9; ? ; count = count - 1)


cout << count << endl;

12
The second section of the loop requires some thought. If we keep subtracting 1 from the value in count
(starting from 9), we will eventually get to 3, 2, 1, 0, -1, -2, -3, and the numbers will keep going more in
the negative direction. However, we need to stop at zero. Thus, the expression for the second section of
the for loop can be written as:

count >= 0;

This means that we keep repeating the for loop as long as the value of count is greater than or equal to
zero. The for loop to generate the numbers in descending order is given below:

for (count = 9; count >= 0 ; count = count - 1)


cout << count << endl;

13
5.7 Exercises

1. Write a program to generate a conversion table from miles per hour to kilometres per hour. The
starting value should be 10 miles per hour and the ending value should be 100 miles per hour. The
conversion table should be displayed in increments of 5 miles per hour. Assume that 1 mile = 1.6
kilometres.

2. Write a program to generate a conversion table from degrees to radians. The starting value should
be 0 degrees and the ending value should be 360 degrees. The user should specify the increment of
degrees in the table. To convert from degrees to radians, multiply the degree value by π (3.14159)
and divide by 180.

3. Write a program which displays the numbers 13 through 60 on the monitor, four numbers per line.
The output should be as follows:

13 14 15 16
17 18 19 20
21 22 23 24
25 26 27 28
29 30 31 32
33 34 35 36
37 38 39 40
41 42 43 44
45 46 47 48
49 50 51 52
53 54 55 56
57 58 59 60

4. Write a program which displays all the even numbers between 2 and 100 on the monitor, one per
line.

5. Write a program which displays the following sequence of numbers on the monitor:

2
4
8
16
32
.
.
.
1024

14

Вам также может понравиться