Sample Program: Using a Flag to Control a Loop

//  This program prompts the user to enter the cost of each item purchased.
//  When the user has no more items he or she should enter -1 for the cost.
//  The total cost of all items will then be printed.

#include <iostream.h>
#include <iomanip.h>

int main()
{
   const int SENTINEL = -1;
   float price;
   float total;

   total = 0;

//  read in the price of each item and add it to the total
   cout << "Enter the price of the first item (enter -1 to end): ";
   cin >> price;
   while (price != SENTINEL)
   {
      total = total + price;
      cout << "Enter the price of the next item (enter -1 to end): ";
      cin >> price;
   }

//  print the total cost
   cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint);
   cout << setprecision(2);

   cout << "The total cost of all items purchased is:   $ ";
   cout << total;

   return 0;
}


//  This version of the program uses a flag to control the while loop

#include <iostream.h>
#include <iomanip.h>

int main()
{
   const int SENTINEL = -1;

//  flag to indicate when the loop should end
   int done;
   float price;
   float total;

   total = 0;

//  read in the price of each item and add it to the total
   cout << "Enter the price of the first item (enter -1 to end): ";
   cin >> price;
   if (price == SENTINEL)
      done = 1;
   while (!done)
   {
      total = total + price;
      cout << "Enter the price of the next item (enter -1 to end): ";
      cin >> price;
      done = (price == SENTINEL);
   }

//  print the total cost
   cout << setiosflags(ios::fixed);
   cout << setiosflags(ios::showpoint);
   cout << setprecision(2);

   cout << "The total cost of all items purchased is:   $ ";
   cout << total;

   return 0;
}

Sample Execution:

Enter the price of the first item (enter -1 to end): 2.25
Enter the price of the next item (enter -1 to end): 3.50
Enter the price of the next item (enter -1 to end): 1.75
Enter the price of the next item (enter -1 to end): 4.25
Enter the price of the next item (enter -1 to end): -1
The total cost of all items purchased is:   $ 11.75


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002