Lab 7 -- While Loop Construct

Click Here to CREATE ANSWER SHEET for LAB 7


Objectives:
Sections:
  1. Introduction
  2. Counting and Accumulating
  3. The C++ While Loop Syntax
  4. Count-Controlled While Loop
  5. Sentinel-Controlled While Loop
  6. End-of-file-Controlled While Loop
  7. Flag-Controlled While Loop
  8. Event Controlled While Loops that are not Sentinel, EOF, nor Flag Controlled
  9. Designing While Loops
  10. Finding Errors in While Loops
  11. Nested While Loops

Introduction
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:

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
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:


int howmany;        // declare the variable that will do the counting
howmany = 0;        // initialize to zero

int age;            // age of an individual
int sum;            // used to total/accumulate ages
sum = 0;            // initialize total to zero

cout << "Please enter age of individual: ";
cin >> age;

sum = sum + age;    // add age to existing sum
++howmany;          // count the individual

  

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 C++ WHILE Loop
The while loop construct:

C++ Syntax of While Loop: while (logical expression)      //the logical expression is the test condition
statement;

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.


Count-Controlled WHILE Loop
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.

Exercise 2:
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.

Exercise 3.P (Note this is a posttest question):
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

Exercise 4.P:
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
An event-controlled while loop may use a special data value, sentinel, in conjunction with the logical expression to signal the loop exit. As long as the sentinel value does not meet the logical expression (specified data value), the loop is executed. This looping construct is referred to as a 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 5:
For the code given in Example 2 above, what is printed for the input data: a, b, c, d, e, q (the commas and blanks are not part of the data). There is space provided on the answer sheet for your answer.

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
A while loop is often used to repeatedly read data. When a program uses a stream to read data, the stream state (as described in Chapter 5 Section 5) is set after each read from the input data stream. After the last data item has been read from the input data stream, the data stream state is fine. But the next attempt to read input data from the stream will cause an end-of-file (EOF, for short) to be encountered. At this time the data stream enters a fail state. This state can be used to determine the end of data by using the stream name as a boolean variable to access the current stream state. Thus the stream name, when used in a logical expression, indicates the success of the most recent I/O. The stream state will show failure when the end-of-file is reached. On Unix systems, a ctrl-D keyboard input indicates end of data stream (when reading from the keyboard), and on Window systems a ctrl-Z indicates end of data stream (when reading from the keyboard). When a while loop is used to repeatly read data and the stream state is used to terminate the loop, i.e., the stream state is used as the event in the while loop, the while loop is refered to as an 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; 
    } 

        a.    false 
        b.    true 
        c.    the same value as number 
        d.    the same value as sum 
        e.    an arbitrary value 



General Event-Controlled WHILE Loop
As noted in the introduction of this lab, controlled loops may use any logical expression to control execution of the loop. We have classified certain event controlled loops as sentinel, end-of-file-controlled, and flag-controlled while loops. The following is an example of a while loop that is a general event controlled 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.


Exercise 12:
Re-write Example 5 above so as to find the average of input data items (integers) between 0 and 100 inclusive. Stop the loop when an input data item is not between 0 and 100 inclusive. Display the average. Place your answer on the answer sheet.

Designing WHILE Loops
Now that you are familiar with the while loop, make sure that you can distinguish between each control type and when each control structure should be used. A programmer should ask the following questions when writing a program:

If a loop is needed:




Exercise 13:
Look at each of the following problems and answer the questions for each. Do not write code !

a.    Ask the user to type in a word, one character at a time, and print how many uppercase letters are contained in the word. The word is terminated by a carriage return. Hint: The computer should continue to read in one character at a time and count those that are upper-case characters until a carriage return is read.
  1.     What is the loop's logical expression?
  2.     What needs to be updated in the logical expression?
  3.     What control form of the while loop should be used, i.e., count, sentinel, EOF, flag, or other event controlled?
  4.     Why was this particular construct chosen?
  5.     What needs to be initialized before the while loop?
  6.     What should be placed inside the loop?
  7.     What is known when the loop finishes?

b.    You have 30 employees in your company and you wish to write a note to each one of them and inform them of their new salary increases. It is necessary to read in an employee's name and salary increase and print a letter for each.
  1.     What is the loop's logical expression?
  2.     What needs to be updated in the logical expression?
  3.     What control form of the while loop should be used?
  4.     Why was this particular construct chosen?
  5.     What needs to be initialized before the while loop?
  6.     What should be placed inside the loop?
  7.     What is known when the loop finishes?

Exercise 14.P:
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


Finding Errors
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?

        n = 0; 
        while (n < 5) 
        { 
            cout << n << ' '; 
        } 

        a.    0 1 2 3 4 
        b.    0 1 2 3 4 5 
        c.    1 2 3 4 
        d.    1 2 3 4 5 
        e.    0 0 0 . . . forever


Nested While Loops
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.

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.


	
//File:      cla7b.cc
//Author:
//Purpose:   This program counts the number of lines and characters
//           found in the input.

//include files...
#include <iostream>

using namespace std;

int main()
{
    int LineCounter;           // counts the number of lines                   
    int CharCounter;           // counts the number of chars 
    char letter;               // letter that is read                          

    LineCounter = 0;           // initialize the line counter                  
    CharCounter = 0;           // initialize the char counter                
    cin.get(letter);           // read first letter                            

    while ( cin )              // loop until failed data stream read           
    {                                                                          
       while ( cin && letter != '\n' )
       {
           ++CharCounter;      // count the letter just read                   
           cin.get(letter);    // read next letter 
       }                                                                       
       cin.get(letter);        // read next letter                             
       ++LineCounter;          // count the line read                          
    }                                                                          
    cout << "There were " << LineCounter << " lines read with a total of "     
         << CharCounter << " characters." << endl;                
    return 0;
}


Exercise 16:
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.

Exercise 17.P:
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 



Congratulations! You have reached the end of Lab 7.