Sample Program: Incorrect Event Controlled 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.

//  NOTICE THAT THIS PROGRAM GIVES THE WRONG ANSWER!!!!

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

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

//  read in the price of each item and add it to the total
//  ERROR -- THE READ STATEMENT IS IN THE WRONG PLACE SO THE TOTAL WILL BE WRONG
   while (price != SENTINEL)
   {
      cout << "Enter the price of the next item (enter -1 to end): ";
      cin >> price;
      total = total + price;
   }

//  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:   $ 10.75


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

© Copyright Emmi Schatz 2002