Sample Program: For Loop

//  This program prompts the user to enter the cost of each item
//  purchased. It will read in the cost of exactly 6 items using a for
//  loop. The total cost of all items will then be printed.

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

int main()
{
   float price;
   float total;
   int numberOfItems;

   total = 0;

//  read in the price of each item and add it to the total
   for (numberOfItems = 1 ; numberOfItems <= 6 ; numberOfItems++)
   {
      cout << "Enter the price of the next item: ";
      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 next item: 4.5
Enter the price of the next item: 1.99
Enter the price of the next item: 11.95
Enter the price of the next item: 2.5
Enter the price of the next item: 4.59
Enter the price of the next item: 7.75
The total cost of all items purchased is:   $ 33.28


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

© Copyright Emmi Schatz 2002