1. Evaluating mathematical series (cont'd)

Example 2

Goal: Write a procedure addPairs(n) which computes the sum of the first n terms in:
       
      1*3 + 4*6 + 7*12 + 10*24 + ...
As in the previous examples we have a summation of individual "bobs" (quantities). The major difference is that each "blob" is the product of two numbers. It is difficult to keep track of the "blob" on its own, but we can we keep track of its components which will help us figure out the value of the "blob" that needs to be added to the overall result: In summary: * each blob is a product of two numbers (will call them first and second) * first increases by 3 at each step (start with value 1) * second doubles at each step (start with value 3) To solve the problem we need to:
* keep track of - total/result so far (initially 0) - first component of our "blob" that we need to add (initially 1) - second component of our blob that we need to add (initially 3) * update the variables - result <-- result + curNum (where curNum <-- first*second) - first <-- first + 3 - second <-- second * 2
The final code is:
int addPairs( int n )
{
     int result = 0;

     int first = 1;       // first component of the pair  (the 1 in 1*3)
     int second = 3;      // second component of the pair (the 3 in 1*3)

     int count = 0;       // how many terms added so far

     while ( count < n )
     {
          int curNum = first*second;   // compute the "blob" from its parts
          result = result + curNum;    // add blob to overall result

          first = first + 3;           // update the "blob"s parts
          second = second * 2;

          count = count + 1;           // one more "blob" added
     }
 
     return result;
}