1 / 36

C++ for the MFE class at UC Berkeley Session #3 4-20-2006

C++ for the MFE class at UC Berkeley Session #3 4-20-2006. Yuli Kaplunovsky MFE, MBA, MS-Tax, CFA yuli@FinancialSimulations.com (408) 884 5965. Example - simple class. #include <iostream> using namespace std; class cl { int i; // private by default public: int get_i();

seanna
Download Presentation

C++ for the MFE class at UC Berkeley Session #3 4-20-2006

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ for the MFE class at UC BerkeleySession #3 4-20-2006 Yuli Kaplunovsky MFE, MBA, MS-Tax, CFA yuli@FinancialSimulations.com (408) 884 5965

  2. Example - simple class #include <iostream> using namespace std; class cl { int i; // private by default public: int get_i(); void put_i(int j); }; int cl::get_i() { return i; } void cl::put_i(int j) { i = j; } int main() { cl s; s.put_i(10); cout << s.get_i() <<endl; return 0; } http://www.cs.uregina.ca/Links/class-info/cplusplus/CExample.html

  3. Example – new / delete #include <iostream> #include <cstdlib> using namespace std; class myclass { int *p; public: myclass(int i); ~myclass(); int getval() { return *p; } }; myclass::myclass(int i) { cout << "Allocating p\n"; p = new int; if(!p) { cout << "Allocation failure.\n"; exit(1); // exit program if out of memory } *p = i; } myclass::~myclass() { cout << "Freeing p\n"; delete p; } void display(myclass ob) { cout << ob.getval() << '\n'; } int main() { myclass a(10); display(a); return 0; }

  4. Example – Input/output #include <iostream> using namespace std; int main() { float gallons, liters; cout << "Enter number of gallons: "; cin >> gallons; // Read the inputs from the user liters = gallons * 3.7854; // convert to liters cout << "Liters: " << liters << endl; return 0; }

  5. Example – char array #include <iostream> #include <stdlib.h> using namespace std; int main() { char name[32]; // big enough to hold 32 characters // prompt for the name cout << "What's your name?" << endl; gets(name); // read a string from the key board. cout << "Hello! " << name << "!" << endl; return 0; }

  6. Example – 2D array #include <iostream> using namespace std; int main() { int sqrs[10][2] = { {1, 1}, {2, 4}, // The square of 2 is 4,and so on {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49}, {8, 64}, {9, 81}, {10, 100} }; int i, j; cout << "Enter a number between 1 and 10: "; cin >> i; // look up i for(j = 0; j < 10; j++) if(sqrs[j][0] == i) break; // break from loop if i is found cout << "The square of " << i << " is " ; cout << sqrs[j][1] << endl; return 0; }

  7. Example - Pointers #include <stdio.h> typedef struct { int X,Y,Z; } cord_struct; int MyFunc( cord_struct *P ) { return P->X + P->Y; } void main() { int J,K,L; cord_struct Cord[10]; for ( J = 0 ; J < 10 ; J++ ) { Cord[J].X = J*2; Cord[J].Y = J*3 + 1; } K = MyFunc( &Cord[0] ); L = MyFunc( &Cord[1] ); printf("%d,%d\n", K,L); }

  8. Example – Array of strings #include <iostream> using namespace std; // function prototyping int menu(); // funciton to display the menu void enter(); // function to enter info void report(); // function to print report // Global variables: char name[2][80]; // this array holds employee names char phone[2][20]; // their phone numbers float hours[2]; // hours worked per week float wage[2]; // wage int choice; int main() { do { choice = menu(); // get selection switch(choice) { case 0: break; case 1: enter(); break; case 2: report(); break; default: cout << "Try again.\n\n"; } } while(choice != 0); return 0; }

  9. int menu()// Return a user's selection. { int choice; cout << "0. Quit\n"; cout << "1. Enter information\n"; cout << "2. Report information\n"; cout << "\nChoose one: "; cin >> choice; return choice; } void enter()// Enter information. { for(int i=0; i<2; i++) { cout << "Enter last name: "; cin >> name[i]; cout << "Enter phone number: "; cin >> phone[i]; cout << "Enter number of hours worked: "; cin >> hours[i]; cout << "Enter wage: "; cin >> wage[i]; } } void report()// Display report. { for( int i=0; i<2; i++) { cout << name[i] << ' ' << phone[i] << '\n'; cout << "Pay for the week: " << wage[i] * hours[i] << ‘\n’; } 0. Quit 1. Enter information 2. Report information Choose one: 1 Enter last name: Smith Enter phone number: 5556666 Enter number of hours worked: 30 Enter wage: 23.40 Enter last name: Bush Enter phone number: 6668888 Enter number of hours worked: 20 Enter wage: 40.00 0. Quit 1. Enter information 2. Report information Choose one: 2 Smith 5556666 Pay for the week: 702 Bush 6668888 Pay for the week: 800 0. Quit 1. Enter information 2. Report information Choose one: 0

  10. Reference in a function // function definition for swap() void swap(int &i, int &j) { int temp; temp = i; i = j; j = temp; } #include <iostream> using namespace std; void swap(int &i, int &j); // function prototype swapping two values int main() { int NumOne = 0; int NumTwo = 0; cout << "Please enter two integers: " << endl; cout << "Enter value for NumOne: " ; cin >> NumOne; cout << "Enter value for NumTwo: " ; cin >> NumTwo; cout << "Before swapping, NumOne is: " << NumOne << endl; cout << "Before swapping, NumTwo is: " << NumTwo<< endl; swap(NumOne, NumTwo); cout << "After swapping, NumOne is: " << NumOne << endl; cout << "After swapping, NumTwo is: " << NumTwo<< endl; return 0; } Please enter two integers: Enter value for NumOne: 10 Enter value for NumTwo: 20 Before swapping, NumOne is: 10 Before swapping, NumTwo is: 20 After swapping, NumOne is: 20 After swapping, NumTwo is: 10

  11. simple inheritance #include <iostream> using namespace std; class base { int i, j; public: void set(int a, int b) { i = a; j = b; } void show() { cout << i << " " << j << "\n"; } }; // inheritance class derived : public base { int k; public: derived(int x) { k = x; } void showk() { cout << k << "\n"; } }; void main() { derived ob(3); ob.set(1, 2); // access member of base ob.show(); // access member of base ob.showk(); // uses member of derived class } Output: 1 2 3

  12. Using protected members class base { protected: int i, j; // private to base, but accessible to derived public: void set(int a, int b) { i = a; j = b; } void show() { cout << i << " " << j << "\n"; } }; class derived : public base { int k; public: // derived may access base's i and j void setk() { k = i*j; } void showk() { cout << k << "\n"; } }; void main() { derived ob; ob.set(2, 3); // OK, known to derived ob.show(); // OK, known to derived ob.setk(); ob.showk(); } Output: 2 3 6

  13. Protected inheritance class base { int i; protected: int j; public: int k; void seti(int a) { i = a; } int geti() { return i; } }; // Inherit base as protected. class derived : protected base { public: void setj(int a) { j = a; } // j is protected here void setk(int a) { k = a; } // k is also protected int getj() { return j; } int getk() { return k; } }; int main() { derived ob; /* This next line is illegal because seti() is a protected member of derived, which makes it inaccessible outside of derived. */ // ob.seti(10); // cout << ob.geti(); // illegal -- geti() is protected // ob.k = 10; // also illegal because k is protected // these next statements are OK ob.setk(10); cout << ob.getk() << ' '; ob.setj(12); cout << ob.getj() << ' '; return 0; } Output: 10 12

  14. Multiple inheritance class base1 { protected: int x; public: void showx() { cout << x << "\n"; } }; class base2 { protected: int y; public: void showy() { cout << y << "\n"; } }; // Inherit multiple base classes. class derived: public base1, public base2 { public: void set(int i, int j) { x = i; y = j; } }; int main() { derived ob; ob.set(10, 20); // provided by derived ob.showx(); // from base1 ob.showy(); // from base2 return 0; } Output: 10 20

  15. Calling base class's constructor in derived class  class base1 { protected: int i; public: base1(int x) { i = x; cout << "Constructing base1\n"; } ~base1() { cout << "Destructing base2\n"; } }; class base2 { protected: int k; public: base2(int x) { k = x; cout << "Constructing base2\n"; } ~base2() { cout << "Destructing base2\n"; } }; class derived: public base1, public base2 { int j; public: derived(int x, int y, int z): base1(y), base2(z) { j = x; cout << "Constructing derived\n"; } ~derived() { cout << "Destructing derived\n"; } void show() { cout << i << " " << j << " " << k << "\n"; } }; int main() { derived ob(3, 4, 5); ob.show(); // displays 4 3 5 return 0; } Constructing base1 Constructing base2 Constructing derived 4 3 5 Destructing derived Destructing base2 Destructing base2

  16. Calling base class's constructor in derived class  #include <iostream> #include <cstring> using namespace std; class B_class { char author[80]; public: void put_author(char *s) { strcpy(author, s); } void show_author() { cout << author << "\n"; } } ; class D_class : public B_class { char title[80]; public: void put_title(char *num) { strcpy(title, num); } void show_title() { cout << "Title: "; cout << title << "\n"; } }; void main() { B_class *p; B_class B_ob; D_class *dp; D_class D_ob; p = &B_ob; // address of base // Access B_class via pointer. p->put_author("Tom Clancy"); // Access D_class via base pointer. p = &D_ob; p->put_author("William Shakespeare"); // Show that each author went into proper object. B_ob.show_author(); D_ob.show_author(); cout << "\n"; dp = &D_ob; dp->put_title("The Tempest"); p->show_author(); // either p or dp can be used here. dp->show_title( ); } Output: Tom Clancy William Shakespeare William Shakespeare Title: The Tempest Since put_title() and show_title() are not part of the base class, they are not accessible via the base pointer p and must be accessed either directly, or, as shown here, through a pointer to the derived type.

  17. Virtual functions class triangle : public figure { public: void show_area() { cout << "Triangle with height "; cout << x << " and base " << y; cout << " has an area of "; cout << x * 0.5 * y << ".\n"; } }; class square : public figure { public: void show_area() { cout << "Square with dimensions "; cout << x << "x" << y; cout << " has an area of "; cout << x * y << ".\n"; } }; class circle : public figure { public: void show_area() { cout << "Circle with radius "; cout << x; cout << " has an area of "; cout << 3.14 * x * x << ".\n"; } } ; class figure { protected: double x, y; public: void set_dim(double i, double j=0) { x = i; y = j; } virtual void show_area() { cout << "No area computation defined "; cout << "for this class.\n"; } } ;

  18. int main() { figure *p; // create a pointer to base type triangle t; // create objects of derived types square s; circle c; p = &t; p->set_dim(10.0, 5.0); p->show_area(); p = &s; p->set_dim(10.0, 5.0); p->show_area(); p = &c; p->set_dim(9.0); p->show_area(); return 0; } Triangle with height 10 and base 5 has an area of 25. Square with dimensions 10x5 has an area of 50. Circle with radius 9 has an area of 254.34.

  19. Financial applications - Normal Distribution // **************************************************** // **************************************************** double N_func( double X ) // The cumulative normal distribution { double L, K, w ; double const a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937; double const a4 = -1.821255978, a5 = 1.330274429; L = fabs(X); K = 1.0 / (1.0 + 0.2316419 * L); w = 1.0 - 1.0 / sqrt(2 * Pi) * exp(-L *L / 2) * (a1 * K + a2 * K *K + a3 * pow(K,3) + a4 * pow(K,4) + a5 * pow(K,5)); if (X < 0 ) w= 1.0 - w; return w; }

  20. Black Scholes(there is a mistake) double BS( double S, double K, double Sig, double t, double r ) { double d1, d2; double t_sqrt = sqrt(t); d1 = (log(S/K) * r * t) / (Sig * t_sqrt ) + 0.5 * Sig * t_sqrt; d2 = d1 - (Sig*t_sqrt); return S * N_func(d1) - K * exp( -r * t ) * N_func(d2); }

  21. fopen, fprintf, fclose • Use ‘pointer’ to predetermined structureFILE *F; • To create / open file: F = fopen( “file_name”, “type” );examples:F = fopen(“file1.dat”, “w” );F_Read = fopen(“file2.dat”,”r” ); • ALWAYS need to close the file before program terminatesfclose( F ); • One way to write to a file – very similar to printf();fprintf( F, “test\n” );

  22. File write example #1 A new file by the name ‘file1.dat’ is created, and its content is: ABCDE Second Line 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, #include <stdio.h> void main() { FILE *F; int I; F = fopen("file1.dat", "w" ); fprintf( F, "ABCDE\n" ); fprintf( F, "Second Line\n" ); for ( I = 0 ; I < 10 ; I++ ) fprintf( F, "%d, ", I); fclose(F); }

  23. File read example #2 The content of the file ‘num10.dat’: 10 20 30 40 99 32 1 999 -22 4423 #include <stdio.h> void main() { FILE *F; int I, J; F = fopen("num10.dat", "rt" ); printf("Reading from the file:\n"); for ( I = 0 ; I < 10 ; I++ ) { fscanf( F, "%d" , &J ); printf( "%d, ", J ); } fclose(F); } Output (on the monitor): Reading from the file: 10, 20, 30, 40, 99, 32, 1, 999, -22, 4423,

  24. The content of the file ‘num10.dat’: 1,10.2 3, 20 5, 30.33 1,2 22 , 333 45,46 9 40.11 3,-993.3333 99,33.2 Output (on the monitor): Reading from the file: 1,10.2 3,20 5,30.33 1,2 22,2 45,46 9,46 3,-993.333 File read example #3 #include <stdio.h> void main() { FILE *F; int I, J; char ST[200]; float FL; double D; F = fopen("num20.dat", "rt" ); printf("Reading from the file:\n"); for ( I = 0 ; I < 8 ; I++ ) { fgets( ST, sizeof(ST)-1, F ); sscanf( ST, "%d,%f" , &J, &FL ); D = FL; printf( "%d,%g \n", J, D ); } fclose(F); }

  25. malloc / free #include <stdlib.h> void main() { double *D; int I; D = (double *)malloc( sizeof(D) * 100 ); for ( I = 0 ; I < 100 ; I++ ) D[I] = (double)I * 1.2; free(D); }

  26. Write file example #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double X,Y; } CORD_typedef; int Generate_Sin_Noise( int N, char *FileName ) { FILE *F; int I; CORD_typedef *C; F = fopen(FileName, "w" ); if ( F == NULL ) return -1; // An Error C = (CORD_typedef *) malloc( sizeof(CORD_typedef) * N ); if ( C == NULL ) { fclose(F); return -1; // An Error } for ( I = 0 ; I < N ; I++ ) { C[I].X = (double)I / 30; C[I].Y = ((I==0)? 0 : C[I-1].Y) / 10.0 + (double)(rand() % 1001) / 100 + sin( C[I].X ) * 3.0; } for ( I = 0 ; I < N ; I++ ) fprintf( F, "%g,%g\n", C[I].X, C[I].Y ); fclose(F); delete(C); return 0; } void main() { if ( Generate_Sin_Noise( 200, "TestSin.dat" ) != 0 ) { printf("Error\n"); exit(-1); } printf("Done \n"); }

  27. From excel to C Output: 0: 192606, -12.31, 0.88 1: 192607, -19.3, -6.24 2: 192608, -13.04, -2.83 889: 200007, -3.55, 1.72 890: 200008, -5.91, -5.17 891: 200009, -10.62, -7.07 892: 200010, -5.03, 1.58 893: 200011, -5.7251, 0.245714 #include <stdio.h> void main() { FILE *F; char ST[300]; int ItemsNum,I; struct { int Month; double P1,P2; } Item[1000]; float F1,F2; F = fopen("Book1.txt", "rt" ); if ( F == NULL ) { printf("Error opening file\n"); return; } fgets(ST, sizeof(ST), F); // We know that the first line is not used ItemsNum = 0; while ( !feof(F) && ItemsNum < 1000 ) { fscanf( F, "%d %g %g\n" , &(Item[ ItemsNum ].Month), &F1, &F2 ); Item[ ItemsNum ].P1 = F1; Item[ ItemsNum ].P2 = F2; ItemsNum++; } fclose(F); for ( I = 0 ; I < 3 ; I++ ) printf("%d: %d, %g, %g\n", I, Item[ I ].Month, Item[ I ].P1, Item[ I ].P2 ); for ( I = ItemsNum-5 ; I < ItemsNum ; I++ ) printf("%d: %d, %g, %g\n", I, Item[ I ].Month, Item[ I ].P1, Item[ I ].P2 ); }

  28. Exercise / Homework: This was the basic foundation of C++ Spending ONLY 2.5 hours in class is NOT enough to master the foundation… The easiest way to memorize it and get more familiar with it is to – surprisingly simple - COPY all the samples and run them one by one on your PC.

More Related