Sample Program: Count Controlled Loop

//  This program prompts the user to enter the number of items to be
//  purchased. It prompts the user to enter the cost of each item purchased.
//  The total cost of all items will then be printed.

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

int main()
{
   float price;
   float total;
   int numberOfItems;
   int i = 0;
   total = 0;

//  find out how many items the user will enter
   cout << "Enter the number of items to be purchased: ";
   cin >> numberOfItems;

//  read in the price of each item and add it to the total
   while (i < numberOfItems)
   {
      cout << "Enter the price of the next item: ";
      cin >> price;
      total = total + price;
      i = i + 1;
   }

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

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

   return 0;
}

Sample Execution:

Enter the number of items to be purchased: 5
Enter the price of the next item: 3.50
Enter the price of the next item: 2.10
Enter the price of the next item: 1.75
Enter the price of the next item: 2.35
Enter the price of the next item: 5.15

The total cost of all items purchased is:   $ 14.85


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

© Copyright Emmi Schatz 2002