CIS Logo SVC Logo

   Computing & Information Systems


Schoology Facebook        Search CIS Site      Tutorials

Software Design Using C++

Review of Loop Patterns

Answering the Question

Remember that we are trying to rewrite the test program so that the program now has the user interactively enter a list of items to buy. For each item to be purchased, the program should prompt the user to enter the unit price and the number of units of this item to buy. The program should output the cost for each type of item and, at the end, the total cost.

Here is the main function rewritten so that the user is not asked for a number of items to buy after entering a price of zero to end the program. The trick is to move the prompt and data entry for the number of units to just inside the while loop body. Think carefully about the flow of control. This does indeed give exactly what we want as you can tell by drawing and examing a flow chart like that shown below after the main function itself. Follow the arrows to convince yourself that the order of execution is always what we want.

int main(void)
   float Price, TotalCost;
   int Num;

   TotalCost = 0.0;

   cout << "Enter the price for the current item to be purchased (or 0 to quit): ";
   cin >> Price;

   // To be exact, we should use != 0 here, but a negative price is not valid
   // so we can end the program on a negative price as well as zero.
   while (Price > 0)
      cout << "Enter the number of units of this item to be purchased: ";
      cin >> Num;
      Results(Price, Num, TotalCost);
      cout << "Enter the price for the current item to be purchased (or 0 to quit): ";
      cin >> Price;

   cout << "Total cost: " << TotalCost << endl;

   return 0;

[flow chart]

Now that the main function has been completed, see if you can finish the rewrite of the remainder of the program. Click on NEXT for the answer.

You can go back to the overall review listing: Review of Introductory Topics.

Back to the main page for Software Design Using C++

Author: Br. David Carlson with contributions by Br. Isidore Minerd
Last updated: January 15, 2013