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

Repetition with While Loops

This lecture introduces another way to achieve repetition in a program, namely, through the use of a
while loop. A while loop is similar to a for loop and causes a set of statements to be repeatedly

executed until a condition becomes false. It is generally used in situations where the amount of
repetitions is not known beforehand.

10.1 Sequence, Selection, and Repetition

Before discussing while loops, the programming constructs used so far in the course are reviewed. In a
computer program, statements are executed sequentially one after the other, in the same order in
which they are written. It is possible to modify the sequential execution of statements in two ways, by
using selection statements and by using repetition statements. A selection statement causes a set of
statements to be executed if a condition is true and another set of statements to be executed if the
condition is false. A repetition statement causes a set of statements to be repeatedly executed until a
condition becomes false.

These three concepts of sequence, selection, and repetition are the building blocks of all computer
programs. Programs of arbitrary complexity can be built using these concepts. Thus, in order to master
the skill of computer programming, it is important to understand how and when to use the three
concepts of sequence, selection, and repetition. The previous lectures have given several examples of
how these concepts can be used. We now look at another way of achieving repetition in a computer
program.

10.2 The While Loop

The while loop is a repetition construct which causes a statement to be repeatedly executed if a
condition evaluates to true. As in the case with a for loop, the statement to be repeated can be either a
single statement or a compound statement. The general structure of a while loop is as follows:

1
while (condition) {
statement 1;
statement 2;

statement n;
}

The condition can be a relational expression or a compound condition. Relational expressions and
compound conditions were described in detail in the previous lecture.

If the condition is initially false, the while loop is not entered and control goes immediately to the first
statement after the while loop. If the condition becomes false while the loop is executing, the loop
stops executing and control goes to the first statement after the while loop.

We will first look at while loops that achieve the same functionality as some of the for loops in Lecture
5. For example, consider the program which generates a conversion table for temperatures in Celsius to
temperatures in Fahrenheit. The table is generated for Celsius values in the range (-40, 40) in increments
of 5. The flow chart to solve this problem is given in Figure 10.1.

2
Figure 10.1: Flow Chart to Generate Temperature Conversion Table

The logic of the flow chart in Figure 10.1 can be implemented in the following for loop:

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


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

3
A while loop can be used to implement the identical logic as follows:

celsius = -40;

while (celsius < 41) {


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

Figure 10.2 shows how the steps of the flow chart are mapped to the statements of the while loop.

4
Figure 10.2: Mapping of Flow Chart Steps to Program Statements
Figure 10.3 highlights the different parts of the while loop which work together to generate the
conversion table.

Figure 10.3: Different Parts of a While Loop

As another example, consider the for loop which generates a table of squares for the numbers 1
through 12. The for loop is written as follows:

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


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

The following code contains a while loop which generates the same results as the for loop:

count = 1;

while (count < 13) {


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

Essentially, the second section of the for loop becomes the condition of the while loop, the first section
assigns a value to the loop control variable before entering the loop, and the third section (which
specifies how to increment the loop control variable) is written as the last statement inside the while
loop. As long as the condition is true, the statements inside the while loop are repeatedly executed.

5
Before concluding this section, consider what happens if the statement, count = count + 1, is
removed from inside the while loop:

count = 1;

while (count < 13) {


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

The value of count is initially 1 and since 1 < 13, the loop is entered. Inside the loop, the value of count
* count is found and stored in square. The values of count (1) and square (1) are then displayed. The

end of the loop is then reached but before executing the statements in the loop again, the condition is
checked. However, count is still 1, and 1 < 13, so the loop is entered again, resulting in the values of
count (1) and square (1) being displayed once more. This continues on and on, without stopping. So, the
output consists of a set of lines repeatedly displayed on the monitor:

1 1
1 1
1 1
1 1
1 1
1 1
. .
. .
. .

A while loop that does not terminate is called an infinite loop. Since the value of count is always 1, the
condition always evaluates to true and the loop does not terminate. The solution to this problem is to
insert a statement that modifies the value of count. So, eventually, count will reach a value which will
cause the loop condition to become false.

10.3 When to Use a While Loop

The previous section gave two examples where a while loop was used to achieve the same functionality
as a for loop. A for loop is more concise than a while loop and there is also the possibility of forgetting
to change the value of the loop control variable inside the while loop resulting in an infinite loop. So, it
might appear that there is no real need for a while loop. However, there are many situations where it is
easier and more understandable to use a while loop instead of a for loop.

6
If it is known beforehand how many repetitions are required, a for loop should be used. This is referred
to as determinate looping. So, a for loop should be used to generate the equivalent Fahrenheit
temperatures for the range of Celcius temperatures between -40 and 40, since there will be a fixed
number of repetitions. Even if the lower and upper bounds are input by the user at the keyboard, there
will still be a fixed number of repetitions based on these values.

If the amount of repetitions is not known beforehand, a while loop should be used. In the remainder of
this course, we will meet several situations where it is preferable to use a while loop instead of a for
loop. For example, consider the problem of displaying the individual digits of a number input by the
user, one per line. Assume that the user enters 192837 at the keyboard and it is stored in a variable,
num. We can find the last digit by using the remainder operator (%):

remainder = num % 10;

This works out to 7 if num is 192837. So, we have successfully obtained the last digit of num. It would
now be good if we can get rid of the 7 from num and repeat the process with the smaller value of num,
19283. We can get rid of the last digit of num by using integer division:

num = num / 10;

Since num is 192837, num / 10 evaluates to 19283 since integer division truncates the remainder when
num is divided by 10 (7).

By repeatedly dividing by 10, we get to all of the digits of num until num becomes zero. It is better to use
a while loop than a for loop since we do not know beforehand how many digits there are in num. The
condition that must be true in order to keep on looping is, num is not equal to zero. This can be written
as (num != 0). Figure 10.4 shows the flow chart which contains the steps needed to solve the problem.

7
Figure 10.4: Flow Chart to Find and Display Each Digit in a Number

8
The complete program to display each digit of the number entered by the user is given below.

#include <iostream>

using namespace std;

int main ()
{
int num;
int digit;

cout << "Please enter a number:";


cin >> num;

while (num != 0) {
digit = num % 10;
num = num / 10;
cout << digit << endl;
}

return 0;
}

If the number entered by the user is 192837, the following output is generated:

7
3
8
2
9
1

Table 10.1 shows the value of num and digit on each of the six executions of the loop.

Loop num Variable at digit Variable New value of Value


Number Start of Loop num Variable Displayed

Table 10.1: 6 Executions of the Loop

9
It can be observed that the digits are displayed in right-to-left order. It is more difficult to display the
digits in left-to-right order but we will be able to do so later in the course.

Since we did not know beforehand how many times the while loop needs to execute, this type of
looping is known as indeterminate looping. This does not mean that all while loops perform
indeterminate looping. The while loops described in the previous section are all examples of
determinate looping.

Before concluding this section, consider what happens if the number entered by the user is zero. The
while loop is not entered since (num != 0) evaluates to false. Consequently, the output statement

inside the while loop is never executed and the single digit of the number zero, 0, is not displayed. To
solve this problem, we can use an if-then-else statement which deals with the special case of num
being zero:

if (num == 0) {
cout << 0;
}
else {
while (num != 0) {
digit = num % 10;
num = num / 10;
cout << digit << endl;
}
}

In the if-then-else statement above, the while loop is nested within the “else” part of the if-then-
else statement. Thus, it is executed only if num is not zero. If num is zero, the “then” part of the if-

then-else statement displays the single digit of num, which is 0.

10
10.4 Exercises

1. Write a program which uses a while loop to display 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

2. Write a program which uses a while loop to display the even numbers between 2 and 100 on the
monitor, one per line.

3. Write a program which uses a while loop to display the following sequence of numbers on the
monitor:

2
4
8
16
32
.
.
.
1024

4. The number of digits in an integer can be found by counting how many times the integer must be
divided by 10 before obtaining a quotient of 0. Write a program which inputs an integer N, and

(a) Finds and displays the number of digits in N.


(b) Finds and displays the sum of the digits of N. For example, if N is 2367, the sum of its digits is 18.
(c) Finds and displays the product of the digits of N. For example, if N is 236, the product of its digits
is 36.
(d) Determines whether N is mystic. N is mystic if the sum of its digits is equal to the product of its
digits.

11
5. A fixed percentage of water is taken out from a tank each day. Write a program that accepts as
input:
(i) W, representing the amount of water in the tank at the start of the first day
(ii) P, representing the fixed percentage of water taken out of the tank each day

and, starting from the first day, displays the number of the day, the amount of water taken out for
that day, and the amount of water remaining in the tank at the end of that day. Your program
should terminate after 30 days have been displayed or when the amount of water remaining is less
than 100 units, whichever comes first.

For example, if W = 1000, and P = 10, the output should start as follows:

DAY AMT TAKEN AMT REMAINING

1 100 900
2 90 810
3 81 729
... ... ...

6. Write a program which finds the sum and average of a set of positive numbers entered by the user
at the keyboard. We do not know how many numbers there are beforehand; however, a negative
number entered by the user indicates that there are no more values to be entered.

(Hint: See Lecture 6, Section 6.3.)

12

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