Lab 7 -- While Loop Construct
Introduction
C++, as well as many other languages, provide the following three looping constructs:
the while, the do-while and the for loop. In this lab, we will only study the
characteristics and syntax of the while loop.
Counting and Accumulating
The C++ WHILE Loop
Count-Controlled WHILE Loop
Exercise 2:
Exercise 4.P:
In the textbook chapter one, we discussed the building blocks of an algorithm and we
learned that one of those building blocks was a loop.
In this lab we will discuss the C++ while loop. First,
consider the following:
A common task often performed by programs is to count and accumulate items.
For example, if one desire to find the average age of a group of individuals,
one must first determine the number of people and the sum of the ages.
Counting in this case is done simply by adding one to a variable each time a new
individual's age is made available. For example, if one has
int howmany; //declare the variable that will do the counting
howmany = 0; // initialize to zero
then by incrementing the variable howmany by one each time a new age is
encountered one can count the number of individuals. For example,
howmany = howmany + 1; // increment counter by one
or
++howmany; // increment counter by one
can be used to count a new individual. This counting must be done
repeatly for each new individual. To sum the age, one would extend the code
above to the following:
One might ask: "how does one count and accumulate hundreds of items?" The
process used above is impractical, but one can use a loop to accomplish this!
The while loop construct:
C++ Syntax of While Loop:
Note that statement forms the body of the while loop and the logical expression is evaluated to determine if the loop body should be executed.
The statement may be a block (compound) statement which means that
multiple statements may be used if they are enclosed in curley braces,
{ ... }.
The block statement was discussed in Chapter 2. Note that statement
is executed after the logical expression (the test condition) is
evaluated.
Since the logical expression associated with the while loop
is evaluated before any of the
statements in the loop, any variables appearing in the logical expression
must receive values before the while is entered. These variables
may be initialized using an assignment statement prior to the while.
The count-controlled while loop uses a loop control variable in the logical
expression. The loop control variable should be initialized before entering
the while loop, and a statement in the body of the while loop should
increment/decrement the control variable.
Example 1. The following is a count-controlled while loop code
segment. Line numbers are given for reference only. This example also makes
use of the counting and summing techniques given above to find the sum of the first 99 positive integers.
10 int counter, sum; // declare loop counter and sum
11 counter = 1; // initialize the loop counter
12 sum = 0; // initialize the sum
13 while ( counter < 100) // iterate the loop 99 times
14 {
15 sum = sum + counter; // add the value of counter to the existing sum
16 ++counter; // increment the counter
17 }
18 cout << "The sum is " << sum << endl; // Display the sum
The loop counter is counter and is initialized in line 11. It will be
used to count the iterations of the loop and to serve as the value summed. The
while loop's logical expression is counter < 100, and the loop
body consists of lines 14 through 17. The loop counter is incremented in
line 16. Lines 10,11,12 and 18 are not part of the while loop statement.
Lines 11 and 12 initialize
variables (the counting and accumulating variables) that will
be used in the while loop and line 17 displays information calculated
using the while loop. Lines 15 and 16 will only be executed when the
logical expression counter < 100 evalutes to true.
Exercise 1:
Write a C++ code segment using the while loop to find the sum of the integers
73 through 415 inclusive. Display the resulting sum. Be sure to give code to
declare and initialize variables used. Place this answer in the answer sheet you created.
Write a C++ code segment using the while loop to find the sum of the even
integers 2,4,6,8,...,500. Display the resulting sum. Be sure to give code to
declare and initialize variables used. Place this answer in the answer sheet you created.
The logical expression associated with the while loop is evaluated ________________. Place your answer on the answer sheet.
a. before any of the statements in the loop
b. after any of the statements in the loop
c. after the first statement in the loop
d. before the last statement in the loop
e. right in the middle of the loop
What is the output of the following code fragment? Place your answer on the answer sheet.
n = 0; while (n < 5) { n++; cout << n << ' ' ; } |
a. 0 0 0 0 ... forever b. 1 2 3 4 c. 1 2 3 4 5 d. 0 1 2 3 4 e. 0 1 2 3 4 5 |
Sentinel-Controlled WHILE Loop
Example 2. The following is a sentinel-controlled while loop code segment. Line numbers are given for reference only. The while loop reads non-white space until the character q is read. All non-white space characters except the q are counted.
20 char letter; // storage for letters read 21 int counter; // counts the number of letters 22 23 cin >> letter; // read the first letter 24 counter = 0; // initialize the counter 25 while ( letter != 'q') // loop until 'q' is read 26 { 27 ++counter; // increment letter counter 28 cin >> letter; // read next letter 29 } 30 cout << "The number of letters read is " << counter << endl;
The loop sentinel value is q and is checked in the logical expression letter != 'q'. The while loop in Example 2 uses a Priming Read--an input statement that appears before the while loop is entered. We say that line 23 primes the while loop. The variable letter can have a value before the while condition could be evaluated.
Exercise 6:
Write a C++ code segment to read characters from the keyboard until a blank
is read. Use a sentinel-controlled while loop to find the
number of nonblank characters read from the keyboard. Display the number found.
If you have forgotten how to read white space, see closed lab 5. Respond to this question on the answer sheet.
Exercise 7.P:
Given the input data
5 10 20 -1
what is the output of the following code fragment? (All variables are of type int.)
sum = 0;
cin >> number;
while (number != -1)
{
sum = sum + number;
cin >> number;
}
cout << sum << endl;
a. -1 b. 4 c. 34 d. 35
e. some number -unpredictable
End-of-file-Controlled WHILE Loop
Example 3. The following is an end-of-file-controlled while loop code segment. Line numbers are given for reference only.
30 float number; // storage for the number read 31 cin >> number; // read the first number (priming read) 32 while ( cin ) // loop until failed data stream read 33 { 34 cout << "The number read is " << number << endl; // display the number read 35 cin >> number; // read next number 36 }
The loop logical expression is ( cin ) which indicates the success/failure of the last keyboard input. The while loop in Example 3 uses a priming read--an input statement that appears before the while loop is entered.
Exercise 8:
The code given in Example 3 can be found in
cla7a.cc.
Copy this program
to your account (cp $CLA/cla7a.cc . ) and extend it as follows. Count the number of
input data items; sum the input data items, and find the average. Display
the final values for the counter, sum, and average. Use I/O redirection
(see closed lab 5) and test your modified program using the data
file cla7a.txt. Attach a script containing a listing of your modified program
(a script of the cat of your source code), the compile, and
execution using I/O redirection from the input data file cla7a.txt (copy this
file to your account, cp $CLA/cla7a.txt . ).
Exercise 9.P:
Given the following input data followed by control_d (which is the end of file character):
1 2 3 4
what is the output of the following code fragment? (All variables are of type int.)
sum = 0;
cin >> number;
while (cin)
{
sum = sum + number;
cin >> number;
}
cout << sum << endl;
a. 1 b. 4 c. 10
d. no output -- an infinite loop
e. an arbitrary value
Flag-Controlled WHILE Loop
A flag is a boolean variable (only can be set to true or false). If a flag is used in a while loop to control the loop execution, then the while loop is referred to as a flag-controlled while loop. Hence, the end-of-file-controlled while loop is a special case of a flag-controlled while loop.Example 4. The following is a flag-controlled while loop code segment. Line numbers are given for reference only.
40 int sum; // the sum of the numbers read 41 bool done; // used to control the while loop 42 int number; // the number read 43 44 sum = 0; // initialize the sum 45 done = false; // initialize the boolean variable done 46 while ( !done ) // loop while not done 47 { 48 cin >> number; // read next number 49 if ( number > 0 ) // sum number if positive 50 sum = sum + number; // sum the number 51 else 52 done = true; // terminate the loop 53 }
The loop logical expression ( !done ) indicates the loop should be executed as long as done is false.
Exercise 10:
Modify the code given in Example 4 above to sum up nonzero
input data items (integers) and display the results. Place your
answer on the answer sheet.
Exercise 11.P:
Given the following code fragment, what is the value of the variable done after the while loop exits?
sum = 0; done = false; while (!done) { cin >> number; if(number < 0) done = true; else sum = sum + number; } |
|
General Event-Controlled WHILE Loop
Example 5. The following is an event-controlled while loop code segment. Line numbers are given for reference only.
50 int number; // number to be read 51 int sum; // the sum of the numbers read 52 sum = 0; // initialize the sum 53 cin >> number; // read first number 54 while ( number > 0 ) // loop while number read > 0 55 { 56 sum = sum + number; // sum the positive number 57 cin >> number; // read next number 58 }
The while loop logical expression is number > 0 which indicates the loop should be executed as long as the value of number is greater than zero. Note that this example does basically the same as example 4.
Designing WHILE Loops
If a loop is needed:
Exercise 14.P:
Finding Errors
Which loop design would be most appropriate for solving the problem "Count the number of scores stored in a data file that ends with 999"?
a. a count-controlled loop
b. a flag-controlled loop
c. a sentinel-controlled loop
d. an End-of-file-controlled loop
Lastly, common errors encountered when using looping structures will be
studied. Consider the following loop example:
int x;
x = 200;
while (x > 100)
cout << x << endl;
x = x - 10;
Do you see the fatal mistake in this program segment? The above example is
an example of an infinite loop! This loop will continue to print the
value "200" forever because the value for x is never changed. The
programmer forgot the syntax for a while loop. Two statements should
have been placed in the loop but the programmer forgot to surround the
statements with a { and a }. Therefore, there is only one
statement in the loop-- cout << x << endl;
Exercise 15.P:
What is the output of the following code fragment?
|
|
Nested While Loops
Example 6. The following demonstrates a nested while
loop. The first while loop is end-of-file-controlled while loop where as
the inner most (nested) loop is event-controlled.
Exercise 16:
Exercise 17.P:
Since the body of the while loop may consist of general C++ statements, one
while loop may be nested inside of another. This is similar to nested if
statements covered in Chapter 5. As an example, consider the following.
Copy the cla7b.cc program to your account. Modify it so that it only counts
nonblank characters and nonblank lines. Note: a line is nonblank if it has at
least one nonblank character appearing in it. Hint: you will need to use
if statements. Use I/O redirection (see closed lab 5) and test your
modified program on the data file cla7b.txt.
Attach a script containing a listing of your modified program
(a script of the cat of your source code), the compile, and
execution using I/O redirection from the input data file cla7b.txt.
What is the output of the following code? (All variables are of type int.)
i = 0; while (i < 3) { j = 1; while (j < 3) { cout << "i = " << i << " j = " << j; j++; } cout << endl; i++; } |
a. i = 0 i = 1 i = 2 i = 0 i = 1 i = 2 j = 1 j = 2 j = 1 j = 2 b. i = 0 j = 1 i = 0 j = 2 i = 0 j = 3 i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 2 j = 1 i = 2 j = 2 i = 2 j = 3 i = 3 j = 1 i = 3 j = 2 i = 3 j = 3 c. i = 0 j = 1 i = 0 j = 2 i = 1 j = 1 i = 1 j = 2 i = 2 j = 1 i = 2 j = 2 i = 3 j = 1 i = 3 j = 2 d. i = 0 j = 1 i = 0 j = 2 i = 1 j = 1 i = 1 j = 2 i = 2 j = 1 i = 2 j = 2 e. none of the above |