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

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

C Language.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
CS 222 Object Oriented Programming Using C++ Inheritance.
Inheritance in C++ Multiple Base Classes Inheritance By Nouf Aljaffan Reference: Learn C++ from the master, Schildt, second Ed.
Inheritance in C++ Multiple Base Classes Inheritance By: Nouf Aljaffan Edited by : Nouf Almunyif.
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 C workshop #2 functions pointers structures files.
1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
11 Introduction to Object Oriented Programming (Continued) Cats II.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
INHERITANCE IN C++ 3 CSC1201: PROGRAMMING LANGUAGE 2 ASEEL ALHADLAQ_KSU 1.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
Functions Why we use functions C library functions Creating our own functions.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Inheritance in C++ 2 CSC1201: Programming Language 2 1Aseel AlHadlaq_KSU.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
April 11, 2005 More about Functions. 1.Is the following a function call or a function header? calcTotal(); 2.Is the following a function call or a function.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
From C to C++. What is C++ C++ is the work of Bjarne Stroustrup of AT&T Bell Labs. C++ is a mostly upward compatible extension of C that provides: A better.
11 Introduction to Object Oriented Programming (Continued) Cats.
Functions BICSE-6A Mr. Naeem Khalid Lecturer, Dept. of Computing.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
CS1201: Programming Language 2 Classes and objects Inheritance Nouf Aljaffan Edited by : Nouf Almunyif.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
1.  The following class, called road_vehicle, very broadly defines vehicles, that travel on the road. It stores the number of wheels a vehicle has and.
A First Book of C++ Chapter 12 Extending Your Classes.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Chapter 1.2 Introduction to C++ Programming
Polymorphism &Virtual Functions
C++, OBJECT ORIENTED PROGRAMMING
Polymorphism & Virtual Functions
CS1201: Programming Language 2
Popping Items Off a Stack Lesson xx
Pointers, Dynamic Data, and Reference Types
Inheritance.
Multiple Base Classes Inheritance
C Programming - Lecture 3
CECS 130 Final Exam Review Session
Presentation transcript:

C++ for the MFE class at UC Berkeley Session # Yuli Kaplunovsky MFE, MBA, MS-Tax, CFA (408)

2 #include 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; } Example - simple class

3 #include 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 using namespace std; int main() { float gallons, liters; cout << "Enter number of gallons: "; cin >> gallons; // Read the inputs from the user liters = gallons * ; // convert to liters cout << "Liters: " << liters << endl; return 0; } Example – Input/output

5 #include 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; } Example – char array

6 #include 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 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 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; } 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. Quit 1. Enter information 2. Report information Choose one: 1 Enter last name: Smith Enter phone number: Enter number of hours worked: 30 Enter wage: Enter last name: Bush Enter phone number: Enter number of hours worked: 20 Enter wage: Quit 1. Enter information 2. Report information Choose one: 2 Smith Pay for the week: 702 Bush Pay for the week: Quit 1. Enter information 2. Report information Choose one: 0

10 #include 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: 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 Reference in a function

11 #include 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: simple inheritance

12 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: 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: 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: 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 base1 Constructing base2 Constructing derived Destructing derived Destructing base2 Calling base class's constructor in derived class int main() { derived ob(3, 4, 5); ob.show(); // displays return 0; }

16 #include 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 Clancy William Shakespeare Title: 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 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 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

19 Financial applications - Normal Distribution // **************************************************** double N_func( double X ) // The cumulative normal distribution { double L, K, w ; double const a1 = , a2 = , a3 = ; double const a4 = , a5 = ; L = fabs(X); K = 1.0 / ( * L); w = / 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= 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 ) * 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 structure FILE *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 terminates fclose( F ); One way to write to a file – very similar to printf(); fprintf( F, “test\n” );

22 File write example #1 #include 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 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’:

24 The content of the file ‘num10.dat’: 1,10.2 3, 20 5, ,2 22, , , ,33.2 Output (on the monitor): Reading from the file: 1,10.2 3,20 5, ,2 22,2 45,46 9,46 3, #include 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 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 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) / (double)(rand() % 1001) / 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 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: , , : , -19.3, : , , : , -3.55, : , -5.91, : , , : , -5.03, : , ,

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.