36
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

C++ for the MFE class at UC Berkeley Session #3 4-20-2006 Yuli Kaplunovsky MFE, MBA, MS-Tax, CFA [email protected] (408) 884 5965

  • View
    219

  • Download
    6

Embed Size (px)

Citation preview

C++ for the MFE class at UC Berkeley

Session #3 4-20-2006

Yuli Kaplunovsky MFE, MBA, MS-Tax, CFA

[email protected]

(408) 884 5965

2

#include <iostream>using namespace std;

class cl { int i; // private by defaultpublic: 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;}

Example - simple class

http://www.cs.uregina.ca/Links/class-info/cplusplus/CExample.html

3

#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;}

Example – new / delete

4

#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;}

Example – Input/output

5

#include <iostream>#include <stdlib.h> using namespace std;

int main(){

char name[32]; // big enough to hold 32 characters

// prompt for the namecout << "What's your name?" << endl;gets(name); // read a string from the key board.cout << "Hello! " << name << "!" << endl;

return 0;}

Example – char array

6

#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;}

Example – 2D array

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

#include <iostream>using namespace std;

// function prototypingint menu(); // funciton to display the menuvoid enter(); // function to enter infovoid report(); // function to print report

// Global variables:char name[2][80]; // this array holds employee nameschar phone[2][20]; // their phone numbersfloat hours[2]; // hours worked per weekfloat wage[2]; // wageint 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;}

Example – Array of strings

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. Quit1. Enter information2. Report information

Choose one: 1Enter last name: SmithEnter phone number: 5556666Enter number of hours worked: 30Enter wage: 23.40Enter last name: BushEnter phone number: 6668888Enter number of hours worked: 20Enter wage: 40.000. Quit1. Enter information2. Report information

Choose one: 2Smith 5556666Pay for the week: 702Bush 6668888Pay for the week: 8000. Quit1. Enter information2. Report information

Choose one: 0

10

#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;}

// function definition for swap()void swap(int &i, int &j){ int temp;

temp = i; i = j; j = temp;

}

Please enter two integers: Enter value for NumOne: 10Enter value for NumTwo: 20Before swapping, NumOne is: 10Before swapping, NumTwo is: 20After swapping, NumOne is: 20After swapping, NumTwo is: 10

Reference in a function

11

#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"; }};

// inheritanceclass 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 23

simple inheritance

12

class base {protected: int i, j; // private to base, but accessible to derivedpublic: 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 36

Using protected members

13

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; }};

Output:10 12

Protected inheritance

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;}

14

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; }};

Output:1020

Multiple inheritance

int main(){ derived ob;

ob.set(10, 20); // provided by derived ob.showx(); // from base1 ob.showy(); // from base2

return 0;}

15

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"; }};

Constructing base1Constructing base2Constructing derived4 3 5Destructing derivedDestructing base2Destructing base2

Calling base class's constructor in derived class 

int main(){ derived ob(3, 4, 5);

ob.show(); // displays 4 3 5

return 0;}

16

#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"; }};

Output:Tom ClancyWilliam Shakespeare

William ShakespeareTitle: The Tempest

Calling base class's constructor in derived class  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( );}

Since put_title() and show_title() are not partof the base class, they are not accessible viathe base pointer p and must be accessed eitherdirectly, or, as shown here, through a pointer to thederived type.

17

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"; }} ;

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"; }} ;

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

#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);}

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,

23

File read example #2

Output (on the monitor):Reading from the file: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);}

The content of the file ‘num10.dat’:

1020304099321999-224423

24

The content of the file ‘num10.dat’:

1,10.23, 205, 30.331,222 , 33345,469 40.113,-993.333399,33.2

Output (on the monitor):Reading from the file:1,10.23,205,30.331,222,245,469,463,-993.333

#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);}

File read example #3

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

#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");}

Write file example

27

28

29

30

31

32

33

From excel to C#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 );

}

Output:0: 192606, -12.31, 0.881: 192607, -19.3, -6.242: 192608, -13.04, -2.83889: 200007, -3.55, 1.72890: 200008, -5.91, -5.17891: 200009, -10.62, -7.07892: 200010, -5.03, 1.58893: 200011, -5.7251, 0.245714

34

35

36

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.