Ending a Loop

  1. There are roughly three general techniques for ending a loop:

    • Count controlled loop
    • Ask-before-iterating
    • Exit-on-a-flag condition

  2. A count controlled loop first determines the number of iteration before the loop begins and iterates the loop body that many times. This is the best method if the number of iteration is either known or can be predetermined. These loops are best implemented using the for-loop.

  3. The ask-before-iterating method simply ask the user, after each iteration, whether or not the loop should be iterated again. This method is commonly used to process keyboard input.

    The following example for the ask-before-iterating method should be familiar to you:

        char key;
    do
    {
        .
        .
        .
        cout << "Enter a 'y' or a 'Y' if you want to continue,\n";
                << "otherwise enter any other key: ";
        cin >> key;
    } while ((key == 'y') || (key == 'Y'));

  4. There are many variations of the exit-on-a-flag condition.

    • An example is the use of a sentinel value in the input data. The flag condition comes from the sentinel value. We had an example like that when we discussed the while-loop.

    • The flag can also be obtained from detecting whether the end of file is reached. We will consider two separate ways to implement that in C++ in chapter 5, one using the eof member function, and the other using the >> operator.