2012年2月22日 星期三

Exercise #16


Purpose
The purpose of this assignment is
  • To give you practice in using the C++ input/output classes and file I/O.
  • To give you practice in program planning, design and development.
  • To solve a practical "real-world" problem.
Program Description
This program will track a portfolio consisting of three mutual funds over a ten year period. You will invest $10,000 exactly 10 years prior to the date that you run your program. You will use actual mutual fund historical data that you will download as input files to your program.

Requirements
Your must use a main() that is similar to the sample below. The "real work" should not be performed in main().
Your program output file should "logically" match that of the sample output below. You will probably use different mutual funds and run your program for different dates. You must display the initial investment data for your portfolio, the value of the portfolio 5 years ago, 3 years ago, 1 year ago, at the beginning of the year and the current value.
You should turn in the program listing and your output file.
Your solution must contain at least 3 classes, one of which is a "date" class. The "date" class must contain an overloaded insertion operator that "prints" a "date" in an "mm/dd/yy" format.
You are to use the actual downloaded mutual fund historical data. You may not edit this data.
You are to use the closing prices of the mutual on the date of interest. If that date is not a "market open" date, then you must backup and get the previous closing price of the fund.
You must invest at least $3000 in each fund.

References
Yahoo finance page:  http://finance.yahoo.com/
You can look up mutual fund data by entering the "ticker" symbol next to the Get Quotes button at the top of the page. On the mutual fund "Summary" page, use the "Historical Prices" link on the left side of the page to get the history. On the "Historical Prices" page, use the "Download to Spreadsheet" link to download the mutual fund history to a file. Note, the download file is named table.csv, so you need to give it a unique name, since you'll need three different mutual fund history files.

You can find lots of good funds on these sites:
http://bloomberg.com/apps/data?pid=invest_mutualfunds
http://www.kiplinger.com/investing/funds/kip25/tables/index.php
http://www.smartmoney.com/top25funds/http://www.morningstar.com/allanalyses/analysesLists.html?type=FO&fsection=all2000&lpos=Commentary
http://moneycentral.msn.com/investor/research/fundwelcome.asp?Funds=1

Assumptions
Assume that the input data is reliable, that dates and the mutual fund closing prices are valid.
Assume that you do not have access to dividends or capital gains. There is no reinvestment. You give all that money to charity (or the teacher).

Suggestions
Allow 4-12 hours to solve this problem. You will need more time for program planning and analysis than the previous assignments.

Extra Credit
The student with the most valuable portfolio using "today's" closing prices will receive 2 extra credit points. In the event of a tie, only 1 point will be awarded. Remember, actual data must be used for this, but you are free to run the program on different days. By completing the program early, you can pick a day with a good market close.

Sample main()

int main()
{
    Date today;
    Portfolio myPortfolio(today.nYearsBefore(10));
    myPortfolio.addFund("VTSMX",3333.33f,"c:/deanza/data/vtsmx.csv");
    myPortfolio.addFund("VGTSX",3333.33f,"c:/deanza/data/vgtsx.csv");
    myPortfolio.addFund("VBMFX",3333.34f,"c:/deanza/data/vbmfx.csv");
    ofstream fout("c:/deanza/data/ass9.out");
    myPortfolio.report(today,fout);
    return 0;
}

Sample Program Output File

Mutual Funds                        VTSMX       VGTSX       VBMFX       Total      

Initial Investment   06/06/99     3333.33     3333.33     3333.34    10000.00
Initial Shares                    132.380     358.808     572.739    

Value 5 years ago    06/06/04     3243.31     3519.91     4547.55    11310.77
Value 3 years ago    06/06/06     3828.43     5098.67     4874.01    13801.11
Value 1 year ago     06/06/08     4314.27     6562.61     5544.11    16420.98
Value on January 1st 01/01/09     2953.40     3950.48     5715.93    12619.81
Value today          06/06/09     3060.63     4345.17     5738.84    13144.64

Exercise #15


Read in the input file below and produce the report shown.

Input file

John,Doe,123456789,20,21,22,23,16,19,16,50,75
Francisco,Washington,987654321,10,0,20,13,18,19,16,30,70
Tom,Nguyen,111111111,18,23,24,25,17,22,20,38,90
Victoria,Black,333333333,22,21,22,21,20,22,21,45,64
Sally,Seinfield,444444444,17,12,19,23,24,12,11,34,94
Sylvester,De La Rosa,555555555,25,25,24,20,25,25,21,44,80
George,O'Neill,666666666,21,12,3,14,21,14,17,45,99
Sylvia,Smart,777777777,20,21,22,23,24,20,25,44,78
Judy,Yang,888888888,16,19,22,24,25,20,25,45,100
Charles,Black,222222222,20,21,22,22,21,25,16,40,86


                            CIS27 Class Grades Report

Student Name          --- SSN ---  ---- Lab Grades ----  Mid  Fin  Pts   Perct  G
--------------------  -----------  -- -- -- -- -- -- --  ---  ---  ---   -----  -
Doe, John             123-45-6789  20 21 22 23 16 19 16   50   75  246   82.0%  B
Washington, Francisc  987-65-4321  10  0 20 13 18 19 16   30   70  196   65.3%  D
Nguyen, Tom           111-11-1111  18 23 24 25 17 22 20   38   90  260   86.7%  B
Black, Victoria       333-33-3333  22 21 22 21 20 22 21   45   64  238   79.3%  C
Seinfield, Sally      444-44-4444  17 12 19 23 24 12 11   34   94  234   78.0%  C
De La Rosa, Sylveste  555-55-5555  25 25 24 20 25 25 21   44   80  269   89.7%  B
O'Neill, George       666-66-6666  21 12  3 14 21 14 17   45   99  243   81.0%  B
Smart, Sylvia         777-77-7777  20 21 22 23 24 20 25   44   78  257   85.7%  B
Yang, Judy            888-88-8888  16 19 22 24 25 20 25   45  100  280   93.3%  A
Black, Charles        222-22-2222  20 21 22 22 21 25 16   40   86  253   84.3%  B


Program requirements
  • Use C++ input/output techniques and file I/O, no stdio. You should declare one ifstream and one ofstream object.
  • Create at least 3 classes:
    • Name consists of a first and last name.
    • StudentInfo consists of a Name, SSN, 7 lab grades, a midterm, final, and whatever else you want.
    • Class consists of an array of StudentInfo or an array of StudentInfo pointers
  • The rules for calculating points and grades are exactly like the 1st assignment or what was stated on the course syllabus. Remember to discard the lowest lab grade, but not the last one.
  • Use the same input file shown. You may get a copy of the data file in the ATC if you do not want to type it in.
  • Produce exactly the report, with the same spacing, formatting and text. Turn in a copy of the report file along with your program listing.
  • If you are unsure of any program detail, ask the instructor for clarification.

Extra Credit (1 point each)
  • Sort the report by Name (major sort by last name, minor sort by first name)
  • Handle a missing lab score instead of a 0.  Use this record for Francisco Washington: Francisco,Washington,987654321,10,,20,13,18,19,16,60,140
  • Change the lab grades in the input file to octal, but print them out as hexadecimal.

Exercise #14


This assignment will give you practice with C++ input/output classes and file I/O. Use the following program specifications and use the following main() to test your program. You should use the WordFile and the Dictionary classes described below, and any others you wish.

Here is the WordFile class. Write the 4 member functions. Add any others you desire. The getNextWord() function should place the "next word to be read" in the buffer argument and return it. If getNextWord() fails, it should return a null pointer. 

class WordFile {
  private:
    fstream File;
  public:
    WordFile(const char* filename);
    void addWord(const char* word);
    void goToTopOfFile();
    char* getNextWord(char* buffer);
};

The Dictionary class should contain two members, an fstream object and an unsigned int, which stores the number of words in the Dictionary. The Dictionary constructor should use a WordFile& argument. This constructor should read the WordFile's file into memory. Use dynamic memory allocation to temporarily store the words, so they can be sorted. After sorting, write them out to the new Dictionary file and clean up.

Add four more members functions to the Dictionary class, getNumWords(), getDictionarySizeInBytes(), getMiddleWord() and find(). The function, getMiddleWord(), should return the word that's in the middle of the file. That is, if the file is 100 bytes, then the function should return the word that begins on or before byte 50.

Add a friend operator<<() to the Dictionary class. This function should print out the Dictionary.

Use the main() below for the final testing of your program. It, and the sample program run should give you more insight to the program. If you do not complete the program, turn in only the functions and the parts of the program that run, along with the output. Do not turn in a program that does not run.

Test your code thoroughly after you complete each function. Do not attempt the Dictionary class until you WordFile class is complete.

int main() {
  WordFile Words("wordfile.txt");
  char buffer[MaxWordSize];
// Read words into the Word file
  cout << "Enter words for the Word file (“quit” to stop)\n";
  while (cin.getline(buffer,MaxWordSize)&&strcmp(buffer,”quit”))
    Words.addWord(buffer);
  Dictionary Webster(Words);
// Print the Dictionary
  cout << Webster << endl;
// Print the Dictionary size
  cout << "Dictionary size = " << Webster.getDictionarySizeInBytes() << endl;
// Print the word in the middle of the dictionary
  cout << "The middle word is " << Webster.getMiddleWord(buffer) << endl;

// Search for words in the Dictionary
  cout << "Enter words to search for in the Dictionary (“\quit\” to stop)\n";
  cin.clear();
  while (cin.getline(buffer,MaxWordSize) && strcmp(buffer,"quit")) {
    cout << buffer << " is ";
    if (Webster.find(buffer)) cout << "definitely ";
    else cout << "NOT ";
    cout << "in the Dictionary\n";
  }
  return 0;
}

******  Sample Run  ******

Enter words for the Word file (enter "quit" to stop)
chimpanzee
whale
bald eagle
tiger
zebra
mouse
horse fly
mountain goat
baboon
quit
Dictionary Words:
        baboon
        bald eagle
        chimpanzee
        horse fly
        mountain goat
        mouse
        …

Dictionary size = 86            <- Note this could be a different size
The middle word is ???            <- this may vary
Enter words to search for in the Dictionary ("quit" to stop)
elephant
elephant is NOT in the Dictionary
goat
goat is NOT in the Dictionary
baboon
baboon is definitely in the Dictionary
zebra
zebra is definitely in the Dictionary
mountain goat
mountain goat is definitely in the Dictionary
dog
dog is NOT in the Dictionary
quit

Exercise #13


This assignment will give you practice in producing formatted output using C++ input/output classes. Create a class consisting of an int, an unsigned, a long, a short, and a double. Generate random numbers to assign to the members. Print 20 lines of output using the class. Each line should be printed exactly as illustrated below. Of course, the numbers will not match since they are random. The output specifications are:

The first column contains the int member left justified displayed in octal.
The second column contains the unsigned member left justified displayed in hex.
The third column contains the long member left justified displayed in decimal.
The fourth column contains the short member left justified displayed in hex.
The fifth column contains the double member right justified.
The sixth column contains the double member right justified.
The seventh column contains the double member right justified.

The integer types should be printed in a field of width 9, the doubles using a width of 12. Make sure you match the base indicators and the precision of the doubles. 

Note:  for the scientific output shown in the last two columns, your compiler will print the exponent as either a 2-digit or 3-digit number, but not both. You cannot control this. You will have to figure out a way to massage the double value to produce one of the scientific outputs. 

62436    0X22E8   2888     1889         426.0986  4.261e+002   4.26e+02
72062    0X29AF   7884     106c           5.1463  5.146e+000   5.15e+00
47262    0X68E8   19107    5a62           0.9017  9.017e-001   9.02e-01
31237    0X1A6C   29243    2cce          39.5479  3.955e+001   3.95e+01
13020    0X33FD   17339    459d           0.0789  7.890e-002   7.89e-02
74524    0X7E67   8056     5b9e           0.6746  6.746e-001   6.75e-01
45040    0X1842   21039    596            1.3779  1.378e+000   1.38e+00
14051    0X1995   1452     408c           1.8856  1.886e+000   1.89e+00
12706    0X24CE   17308    6bfe           0.0308  3.078e-002   3.08e-02
37534    0X66C5   21689    6e05           0.9871  9.871e-001   9.87e-01
15311    0X2AC5   15003    a87            3.0408  3.041e+000   3.04e+00
56020    0X8D1    3278     200b           0.0388  3.877e-002   3.88e-02
67351    0X23A1   12797    41d1           1.9757  1.976e+000   1.98e+00
76410    0X3908   21582    5a36           0.4780  4.780e-001   4.78e-01
13472    0X42C1   7242     7193           4.8966  4.897e+000   4.90e+00
35644    0X5EDA   16355    350a           2.4271  2.427e+000   2.43e+00
16706    0X7E32   23414    360d           1.0195  1.019e+000   1.02e+00
62433    0X3CC4   26845    667b           1.1618  1.162e+000   1.16e+00
16543    0X1ABC   3301     5eac           0.6685  6.685e-001   6.69e-01
57772    0X5E7E   28111    51be           9.0853  9.085e+000   9.09e+00

Exercise #12


This assignment will give you practice with inheritance and polymorphism.

  1. Create an abstract Solid base class. It should consist of:
    • data members to represent the (x,y,z) coordinates of a solid in 3D space
    • at least one constructor
    • a function that displays the coordinates of a Solid object as (x,y,z)
    • pure virtual functions that:
    • return the volume of the object
      return the surface area of the object
      return the type of the solid
      print "specialized" details about a Solid object (i.e. radius, height, width, …)
    • a non-virtual function that prints all information about a Solid object (it should call the 5 functions listed above)
  2. Derive from the Solid class the following classes:
    • RectangularSolid
    • This class should have three members: length, width, and height.
    • Sphere
    • This class should have one member, radius.
    • Cylinder
    • This class should have two data members, radius and height.
    • Cone
    • This class should have two data members, radius and height.
  3. From the RectangularSolid class, derive a Cube class. It does not have any data members. It only needs a constructor, a type function, and a "print details" function.
You may need the following formulas for this assignment


Use the following main() as a final test of your program:
int main() {
    RectangularSolid        Rec(1.,2.,3.,4.,5.,6.);
    Sphere            Sph(1.,2.,3.,4.);
    Cylinder            Cyl(1.,2.,3.,4.,5.);
    Cone            Con(1.,2.,3.,4.,5.);
    Cube            Cub(1.,2.,3.,4.);
    Solid*            ps;

    // Rectangular Solid test
    ps = &Rec;
    ps->print();

    // Sphere test
    ps = &Sph;
    ps->print();

    // Cylinder test
    ps = &Cyl ;
    ps->print();

    // Cone test
    ps = &Con ;
    ps->print();

    // Cube test
    ps = &Cub ;
    ps->print();
    return 0;
}

******  Program Output  ******

I am a rectangular solid located at (1,2,3)
length=4 width=5 height=6
volume=120 surface area=148

I am a sphere located at (1,2,3)
radius=4
volume=268.082 surface area=???

I am a cylinder located at (1,2,3)
radius=4 height=5
volume=??? surface area=???

I am a cone located at (1,2,3)
radius=4 height=5
volume=??? surface area=???

I am a cube located at (1,2,3)
side=4
volume=64 surface area=???

Exercise #11


This assignment will give you practice with inheritance and polymorphism.

Create the following classes:

GeometricObject:    This is the base class for the other four classes. It should have two protected data members, x and y (coordinates). The class should have the following member functions:
    GeometricObject()    // ctor
    getX()        // accessor function
    getY()        // accessor function
print()
    describeYourself()
    length()
    area()

    All member functions should be const member functions, except the constructor. describeYourself(), length(), and area() functions should be pure virtual functions. The print() function should display the line of output shown below, like
    GeometricObject: 0x????? - location = (x,y)

point    Is derived from GeometricObject and has no data members. Its length() and area() functions should return 0.0.

line    Is also derived from GeometricObject and has two point data members, p1 and p2.  Its constructor must initialize the x,y members of the GeometricObject class. The (x,y) coordinates of a line should be the midpoint of p1 and p2 (take the average of the x coordinates and the average of the y coordinates). Its area() function should return 0.0, but the length() function should return the distance between the two points. Use the formula:

 circle    Is also derived from GeometricObject and has one data member, a double, radius. The constructor should have a point argument and a double argument. The point argument is used to initialize the (x,y) coordinates of the GeometricObject base and the double to initialize the radius.  The length() function should return the circle's circumference and the area() function . r2.

triangle    Is also derived from GeometricObject and has 3 point data members, p1, p2, and p3. Its constructor should have three (point) arguments, to initialize the data members. It also needs to initialize the GeometricObject's (x,y) coordinates. The (x,y) coordinate for a triangle should be the average of its x coordinates and the average of its y coordinates. Add three private member functions, side1(), side2(), side3() to the class. They should each return a double length of a side. For example, side1() should return the length of the side that is opposite point p1. These functions will be useful for the length() and the area(). The length() should return the triangle's perimeter. Use the following formulas for the area of a triangle:


Use the main() below to test your program. The output should give you an indication of what is expected.

int main(void)
{
  int i;
  Point P(0,0), Q(3,0), R(3,4);
  P.DescribeYourself();
  Line L(Q,R);
  L. DescribeYourself ();
  Circle C(P,3);
  C. DescribeYourself();
  Triangle T(P,Q,R);
  T. DescribeYourself();

// polymorphism testing
  GeometricObject* Obj[6];
  Obj[0] = new Point(2,1);
  Obj[1] = new Point(8,1);
  Obj[2] = new Point(5,5);
  Obj[3] = new Line(P,Q);
  Obj[4] = new Circle(P,2.0);
  Obj[5] = new Triangle(P,Q,R);

  for (i = 0; i < 6; i++) Obj[i]-> DescribeYourself();

  for (i = 0; i < 6; i++) delete Obj[i];

  return 0;
}

******  Program Output  ******

GeometricObject: 0x6a0c4 - location = (0,0)
I am a point

GeometricObject: 0x6a060 - location = (3,2)
I am a line
Length=4

GeometricObject: 0x6a038 - location = (0,0)
I am a circle
Area=28.2743  circumference=18.8496

GeometricObject: 0x69fd4 - location = (2,1.33333)
I am a triangle
Area=6  permeter=12

GeometricObject: 0x6c160 - location = (2,1)
I am a point

GeometricObject: 0x6c180 - location = (8,1)
I am a point

GeometricObject: 0x6c1a0 - location = (5,5)
I am a point

GeometricObject: 0x6b100 - location = (?,?)
I am a line
Length=?

GeometricObject: 0x6c1c0 - location = (?,?)
I am a circle
Area=??????  circumference=??????

GeometricObject: 0x6e100 - location = (?,?)
I am a triangle
Area=?  permeter=??

Extra Credit (1 point0) Add a constructors to the circle class, so that you can create a circle:
using a point and a line - the first point is the center, the circle is tangent to the line.

2012年2月21日 星期二

Exercise #10


This assignment will give you practice with overloaded operator functions.
Create a Date class to represent calendar dates. 
The class should contain the following members:
  • Three unsigned short data members to represent day, month, and year.
  • A static const unsigned short 12-element array containing the number of days in each month.
  • A constructor that initializes the three unsigned short members.
It should contain the following overloaded operator member functions:
  1. A ! operator that prints a Date object using the format mm/dd/yy.
  2. A prefix ++ operator that adds a day to a Date object. It should return the object by reference.
  3. A postfix ++ operator that adds a day to a Date object. It should return the object by value.
  4. A prefix -- operator that subtracts a day from a Date object. It should return the object by reference.
  5. A binary + operator with an unsigned short argument. This function should add a number of days to a date object. Use call(s) to the prefix ++ operator in your function definition. It should return a Date object by value.
  6. A binary - operator with an unsigned short argument. This function should subtract a number of days from a date object. Use call(s) to the prefix -- operator in your function definition. It should return a Date object by value.
  7. A += operator with with an unsigned short argument. This function should add a number of days to a date object. Use call(s) to the prefix ++ operator in your function definition. It should return a Date object by reference.
  8. A == operator that determines if two Date objects are equal. This function should return a bool.
  9. A != operator that determines if two Date objects are not equal. This function should return a bool.
  10. A > operator that determines if the "current" Date object is greater than another Date object. One Date object is greater than another Date object if it occurs after the other object. For example, "03/15/02" > "12/25/01". This function should return a bool.
  11. A binary – operator with a const Date& argument. This function should determine the number of days between two Dates. The function should return an int. For example, "01/03/02" – "12/30/01" . 4 and "12/30/01" – "01/03/02" . -4.
Appropriate member functions should be defined as const member functions

Assumptions
It is not necessary to make leap year corrections for this assignment. Assume that February always has 28 days and that a year is exactly 365 days.
A year value between 0 and 49 represents the years 2000 to 2049. A value between 50 and 99 represents the years 1950 to 1999.

Write a main() that demonstrates each of the overloaded member functions. Your output should demonstrate the validity of each function.