cs1ch3sec6.htm
 

CHAPTER THREE

Analysis and Design : First Steps
 


Section VI: The Sum Pattern Section I : Problem Analysis Section II: Problem Analysis Section III: Patterns Section IV:The While Loop With Priming Read Pattern
Section V: The Counter Pattern Section VII: The Average Pattern Section VIII: The Salary Problem Revisited Section IX: Taking Advantage of Patterns

  


Table of Contents

Learning C++:
An Index of Entry Points


2. The

of C++

A reference document on the basic elements of C++.



3. The Patterns



Index!



Section VI. The Sum Pattern
The next pattern to become familiar with is closely related to and often used in conjunction with the counter pattern. Often we need to get a sum of some set of numbers. For example suppose the manager of the store wants to know the total of the discounted prices. As one might suspect, the pattern to accomplish this summing behavior is quite similar to the counter pattern. First, one must initialize to 0 the variable that will hold the sum, then one must read in the numbers to be summed and add them to the sum variable. Here is the general pattern:

Pattern Name: The Sum Pattern Using a Loop
    Purpose: To calculate the sum of some set of numbers.

    Pattern: Initialize the Sum variable to 0 Use some loop pattern - see Sections 'B' and 'C' above Inside the loop pattern add the following code: Sum variable = Sum Variable + Amount To Add

    Using this pattern we can create an algorithm to add up all the discounted prices

      Set Total Discounted Price to 0
      Get Price
      while Price != -1
      {

        Discounted Price = Price * Discount
        Output Discounted Price
        Total Discounted Price = Total Discounted Price + Discounted Price
        Get Price
      }
      Output Total Discounted Price

    You may have already figured out just by reading this that the Total Discounted Price is calculated by determining each individual discounted price each time through the loop and then adding (each time through the loop) that amount to whatever value is already in Total Discounted Price. That is why this variable needs to be initially set to zero. You should also note that there really are two patterns here - the "while loop with a priming read" pattern and the sum pattern. Finally, note that the output of the total is after the while loop. Were the output to be placed inside the loop, the user would see the total continuously, as it was being updated.

    If any of this is unclear, you are strongly urged to trace the algorithm. Try moving around or deleting various lines in the algorithm and see what happens when you trace.

    Let's make the problem a bit harder before we translate the algorithm into C++ code. Suppose the manager of the store wants to know the total amount that was discounted - the difference between the total original price and the total price after the discount. One way to accomplish this, as hinted by the very description just given (an advantage in writing a clear problem description as part of the analysis phase) would be to add up all the original prices, add up all the discounted prices, and calculate the difference. Here is the modified algorithm:

      Set Original Price Total to 0
      Set Total Discounted Price to 0
      Get Price
      while Price != - 1
      {

        Discounted Price = Price * Discount
        Output Discounted Price
        Original Price Total = Original Price Total + Price
        Total Discounted Price = Total Discounted Price + Discounted Price
        Get Price
      }
      Total Discount = Original Price Total - Total Discounted Price
      Output Total Discounted Price
      Output Original Price Total
      Output Total Discount

    As you can see, we now have two total variables. An algorithm can have as many totals as it needs. Also, each total/sum calculation can occur anywhere inside the while loop as long as the value to be summed has already been calculated or somehow entered into the appropriate variable. In this case, we could have moved the line:

    Original Price Total = Original Price Total + Price

    to the very top of the 'while' loop - just after the "while Price != -1" line. Of course, it could not be the last line in the while loop because we would then have lost the first price and at the end we would be adding -1 to the total. (If this is not clear, you know what to do.)

    The other summation line could be placed anywhere inside the loop after the line that calculates the Discounted Price. Note that 'Total Discount' must be calculated after the 'while' loop but it could be placed anywhere from the end of the loop to just before its output line. What you are discovering here is that a particular line of code does not have only one spot in which it can be placed. On the other hand, there is usually some limit to where it can be placed. There is more than one way to write a program but there are definitely 'wrong' ways.

    The translation of this algorithm into C++ is straight forward. As a reminder, however, remember that "X = X + Y" can be translated as "X += Y".

      // A program to calculate sale prices based on a single
      // discount percentage and output the 
      // difference between the original price total and the
      // discounted price total. 
      // File: ch3prg3.cpp
      
      // Use the Specifications from the previous version  and add a  
      // description of the total amount discounted.
      
      #include <iostream.h>
      
      const	double DISCOUNT = .87;
      
      void main()
      // Purpose: 	to calculate sale prices based on a
      //              single discount percentage and output  
      //              the difference between the original price
      //              total and the discounted price total. 
      
      // Receives:	NONE
      // Returns:	NONE
      	
      { 	  
      	double price;
      	double discountedPrice;
      	double totalDiscount;
      	   
              double originalPriceTotal = 0;
      	double discountedPriceTotal = 0;
      	      
              cout << "Please enter an item's original price (Enter -1 to Stop) ";
              cin >> price;
      
              while (price != -1) 
      	{
                	discountedPrice = price * DISCOUNT;
           		cout << "The New Price is: $" <<  discountedPrice << endl;
      		originalPriceTotal += price;
      		discountedPriceTotal += discountedPrice;
      		cout  << "Please enter an item's original price (Enter -1 to Stop) ";
      	        cin >> price;
               }
               totalDiscount = originalPriceTotal - discountedPriceTotal;
      	 cout << "The total of the original prices is: $" <<  originalPriceTotal << endl ;
      	 cout << "The total of the discounted prices is: $" << discountedPriceTotal << endl;
               cout << "The total amount discounted is: $" << totalDiscount << endl;
      }
      
    Some final observations about the sum pattern:
    1. The key to this pattern is contained in the two lines:

        Initialize the Sum Variable to 0
        Sum Variable = Sum Variable + Amount To Add

    2. This pattern usually is related to some loop pattern with this pattern sitting half inside and half outside the loop pattern.

    3. If you had some reason to begin your summing at some value other than zero, that would be possible simply by initializing the sum variable to the other value. Usually sum variables are initialized to 0. However, if, for example, you had already taken the sum of some of the discounted items, knew that the sum at that point was 1,234 and now wanted to finish doing the sum, you might begin the above code fragment by initializing discountedPriceTotal to 1,234 as in:

        int discountedPriceTotal = 1234;

    4. The main difference between the counter and sum patterns is that the counter pattern in a particular piece of code is always incremented by the same amount, for example, by 1 or 5. In contrast, in the sum pattern the sum variable is incremented by a value that is probably different each time through the loop. (Hint: if this sentence is not clear, you probably need to study the two patterns carefully one more time.)

    Top of Section Main Menu Next Section