While Loops

Syntax:

 

while ( logical expression)

statement                                // loop body; usually a compound statement

 

The body of the while loop executes only when the logical expression evaluates to be true.  Most usually there is a variable tested in the logical expression (for example: x<5).  This variable is called the loop control variable. 

 

Three things you need to successfully write a while loop:

 

1.                  INITIALIZE the loop control variable before the while loop

2.                  TEST the loop control variable in the logical expression

3.                  MODIFY the loop control variable in the body of the while loop

 

That is:

 

            Initialize loop control variable (lcv)

            while (test the lcv)

            {

                        statement

                        modify the lcv

                        statement

                        …

            }

 

In the sample programs for this week you will find examples of several different while loops:

 

1.                  count controlled while loop – you know how many pieces of data you are to read

count = 0;                     // initialize

while (count < 10)        // test lcv

{

            …

            count++;          // modify lcv

                                    …

                        }

 

2.                  sentinel controlled while loop – you read data until a special agreed upon value is entered.

The sentinel is like a stop sign – it tells you to stop processing data.  Let’s say the sentinel is -1.

 

cin >> value;                             // initialize

while (value != -1)                    // test lcv

{

            …       

            cin >> value;                 // modify lcv – at some point the user enters the

                                                // sentinel

            …

}

3.                  flag controlled while loop – uses a boolean variable to control the loop.

 

When some condition is satisfied we set the flag so we stop the repetition.  Let’s say the flag is called GotIt.

 

GotIt = false;                                        // initialize

while (!GotIt)                                        // test lcv

{

            …

            if (logical expression)

                        GotIt = true;                 // modify the lcv

            …

}

 

4.                  end of file (eof) controlled while loop

 

you don’t know how many data items will be processed and there is no sentinel

 

cin >> variable;                   // initialize

while (cin)                           // test lcv – is cin active? i.e. did it read a valid value?

{

      …

      cin >> variable; // modify

{

 

while (cin>>variable)          // initialize, test and modify

{

      …

}

 

infile >> variable;

while (!infile.eof())

{

      …

      infile >> variable;

}