Anda di halaman 1dari 71

Solutions Exercises C++ How to program and other.

Mauricio Bedoya javierma36@gmail.com March 2014


Problem and solution is provided, but try to do it yourself rst. Ignore return 0 at the end of the code in main (implemented in Xcode 4.5.2). Book solutions (not all - till chapter 12), begin at Exercise 5.

1.

Exercise 1

Create a class names Data that store two values, and retrieve (with functions) the following operations: addition, multiplication, division. If denominator is zero, throw a message (use close or QL REQUIRE) when division function is called.
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Data { private : Real data1 , data2 ; public : Data ( c o n s t Real& da ta 1 , c o n s t Real& d a t a 2 ) : data1 ( d a t a 1 ) , data2 ( d a t a 2 ) {} Real A d d i t i o n ( ) { r e t u r n data1 + data2 ; } Real M u l t i p l i c a t i o n ( ) { r e t u r n data1 data2 ; } Real D i v i s i o n ( ) { QL REQUIRE( data2 !=0 , data2 i s z e r o , can not implement d i v i s i o n . \ n ) ; r e t u r n data1 / data2 ; } Real D i v i s i o n 1 ( ) { Real r e s u l t ; i f ( ! c l o s e ( data2 , 0 ) ) { r e s u l t = data1 / data2 ; } else

11

13

15

17

19

21

{ c o u t << data2 i s z e r o , can not implement d i v i s i o n . \ n ; } return r e s u l t ; } }; i n t main ( ) { try { Data cout cout cout }

10

12

D( 2 , 0 ) ; << A d d i t i o n : << D. A d d i t i o n ( ) << e n d l ; << M u l t i p l i c a t i o n : << D. M u l t i p l i c a t i o n ( ) << e n d l ; << D i v i s i o n : << D. D i v i s i o n 1 ( ) << e n d l ;

14

16

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

18

2.

Exercise 2

Now create a class with a name Operation (Abstract) with one member function (operate). Cause addition, multiplication and division are operations, implement them via inheritance.
#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Operation { public : v i r t u a l Real o p e r a t e ( ) c o n s t = 0 ; }; c l a s s Addition : p u b l i c Operation { private : Real data1 , data2 ; public : A d d i t i o n ( c o n s t Real& da ta1 , c o n s t Real& d a t a 2 ) : data1 ( d a t a 1 ) , data2 ( d a t a 2 ) {} Real o p e r a t e ( ) c o n s t { r e t u r n data1 + data2 ; } };

10

12

14

16

c l a s s M u l t i p l i c a t i o n : p u b l i c Operation { private : Real data1 , data2 ; public : M u l t i p l i c a t i o n ( c o n s t Real& dat a1 , c o n s t Real& d a t a 2 ) : data1 ( d a t a 1 ) , data2 ( d a t a 2 ) {} Real o p e r a t e ( ) c o n s t { r e t u r n data1 data2 ; } }; c l a s s D i v i s i o n : p u b l i c Operation { private : Real data1 , data2 ; public : D i v i s i o n ( c o n s t Real& da ta 1 , c o n s t Real& d a t a 2 ) : data1 ( d a t a 1 ) , data2 ( d a t a 2 ) {} Real o p e r a t e ( ) c o n s t { QL REQUIRE( data2 !=0 , data2 i s z e r o , can not implement d i v i s i o n . \ n ) ; r e t u r n data1 / data2 ; } }; i n t main ( ) { try { Real data1 = 1 0 , data2 = 1 2 ; A d d i t i o n Add( data1 , data2 ) ; M u l t i p l i c a t i o n Mult ( data1 , data2 ) ; D i v i s i o n Div ( data1 , data2 ) ; c o u t << A d d i t i o n : << Add . o p e r a t e ( ) << e n d l ; c o u t << M u l t i p l i c a t i o n : << Mult . o p e r a t e ( ) << e n d l ; c o u t << D i v i s i o n : << Div . o p e r a t e ( ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

11

13

15

17

19

21

23

25

27

29

31

33

3.

Exercise 3

Same as two, but now implement a class named Data and each function (Addition, Multiplication, Division) will get elds (data1 and data2) from Data. Abstract class remains.
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Operation { public : v i r t u a l Real o p e r a t e ( ) c o n s t = 0 ; }; c l a s s Data { public : Real data1 , data2 ; public : Data ( c o n s t Real& da ta 1 , c o n s t Real& d a t a 2 ) : data1 ( d a t a 1 ) , data2 ( d a t a 2 ) {} v i r t u a l Data ( ) {} }; c l a s s Addition : p u b l i c Operation { b o o s t : : s h a r e d p t r <Data> d ; public : A d d i t i o n ( b o o s t : : s h a r e d p t r <Data>d ) : d ( d ) {} Real o p e r a t e ( ) c o n s t { r e t u r n d>data1 + d>data2 ; } }; c l a s s M u l t i p l i c a t i o n : p u b l i c Operation { b o o s t : : s h a r e d p t r <Data> d ; public : M u l t i p l i c a t i o n ( b o o s t : : s h a r e d p t r <Data>d ) : d ( d ) {} Real o p e r a t e ( ) c o n s t { r e t u r n d>data1 d>data2 ; } }; c l a s s D i v i s i o n : p u b l i c Operation { b o o s t : : s h a r e d p t r <Data> d ; public : D i v i s i o n ( b o o s t : : s h a r e d p t r <Data>d ) : d ( d ) {} Real o p e r a t e ( ) c o n s t { QL REQUIRE( d>data2 !=0 , data2 i s z e r o , can not implement d i v i s i o n . \ n ) ; r e t u r n d>data1 / d>data2 ; } };

11

13

15

17

19

21

23

25

27

29

31

33

35

37

39

41

10

12

14

16

i n t main ( ) { try { Real data1 = 1 0 , data2 = 1 2 ; b o o s t : : s h a r e d p t r <Data> data ( new Data ( data1 , data2 ) ) ; A d d i t i o n Add( data ) ; M u l t i p l i c a t i o n Mult ( data ) ; D i v i s i o n Div ( data ) ; c o u t << A d d i t i o n : << Add . o p e r a t e ( ) << e n d l ; c o u t << M u l t i p l i c a t i o n : << Mult . o p e r a t e ( ) << e n d l ; c o u t << D i v i s i o n : << Div . o p e r a t e ( ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

4.

Exercise 4

Implement the Visit / Visitor patter of exercise 3.


2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Addition { public : A d d i t i o n ( ) {} v o i d a c c e p t ( V i s i t o r <Addition >& A) { V i s i t o r <Addition > A = d y n a m i c c a s t < V i s i t o r <Addition >>(&A) ; i f ( A !=0) A > v i s i t ( t h i s ) ; } }; class Multiplication { public : M u l t i p l i c a t i o n ( ) {} v o i d a c c e p t ( V i s i t o r < M u l t i p l i c a t i o n >& M) { V i s i t o r < M u l t i p l i c a t i o n > M = d y n a m i c c a s t < V i s i t o r < M u l t i p l i c a t i o n >>(&M) ; i f (M !=0) M > v i s i t ( t h i s ) ; } };

10

12

14

16

18

20

22

24

class Division { public : D i v i s i o n ( ) {} v o i d a c c e p t ( V i s i t o r < D i v i s i o n >& D) { V i s i t o r < D i v i s i o n > D = d y n a m i c c a s t < V i s i t o r < D i v i s i o n >>(&D) ; i f ( D !=0) D > v i s i t ( t h i s ) ; } }; template < c l a s s o p e r a t i o n > c l a s s Data : p u b l i c V i s i t o r <o p e r a t i o n >{ public : Real data1 , data2 , R e s u l t ; o p e r a t i o n Oper ; public : Data ( c o n s t Real& da ta 1 , c o n s t Real& d a t a 2 ) : data1 ( d a t a 1 ) , data2 ( d a t a 2 ) {} v i r t u a l Data ( ) {} Real o p e r a t e ( ) { Oper . a c c e p t ( t h i s ) ; return Result ; } v o i d v i s i t ( A d d i t i o n& A) { R e s u l t = data1 + data2 ; } v o i d v i s i t ( M u l t i p l i c a t i o n& M) { R e s u l t = data1 data2 ; } v o i d v i s i t ( D i v i s i o n& D) { QL REQUIRE( data2 !=0 , data2 i s z e r o , can not implement d i v i s i o n . \ n ) ; R e s u l t = data1 / data2 ; } };

11

13

15

17

19

21

23

25

27

29

31

33

35

37

39

41

43

i n t main ( ) { try { Real data1 = 1 0 , data2 = 1 2 ; Data<Addition > Add( data1 , data2 ) ; Data< M u l t i p l i c a t i o n > Mult ( data1 , data2 ) ; Data< D i v i s i o n > Div ( data1 , data2 ) ; c o u t << A d d i t i o n : << Add . o p e r a t e ( ) << e n d l ; c o u t << M u l t i p l i c a t i o n : << Mult . o p e r a t e ( ) << e n d l ; c o u t << D i v i s i o n : << Div . o p e r a t e ( ) << e n d l ; }

45

47

49

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

From here, I will implement the solutions of several exercise found in C++ How to Program (Fifth Edition).

5.

Exercise 5 (3.12 in book)

(Account Class) Create a class called Account that a bank might use to represent customers bank accounts. Your class should include one data member of type int to represent the account balance. [Note: In subsequent chapters, well use numbers that contain decimal points (e.g., 2.75)called oating-point valuesto represent dollar amounts.] Your class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and should ensure that the debit amount does not exceed the Accounts balance. If it does, the balance should be left unchanged and the function should print a message indicating Debit amount exceeded account balance.Member function getBalance should return the current balance. Create a program that creates two Account objects and tests the member functions of class Account. class implemented inline.
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Account { private : int account balance ; void v a l i d a t e ( ) { i f ( a c c o u n t b a l a n c e < 0) { c o u t << E r r o r : Balance i s n e g a t i v e . \ n ; set accountbalance (0) ; } }

10

12

14

16

11

13

15

public : Account ( c o n s t i n t& a c c o u n t b a l a n c e ) : a c c o u n t b a l a n c e ( a c c o u n t b a l a n c e ) { v a l i d a t e () ;} //@ v o i d c r e d i t ( c o n s t i n t& money ) { a c c o u n t b a l a n c e += money ; } v o i d d e b i t ( c o n s t i n t& money ) { i f ( money > a c c o u n t b a l a n c e ) { c o u t << Debit amount e x c e e d a c c o u n t b a l a n c e \ n ; } else { a c c o u n t b a l a n c e = money ; } } v o i d s e t a c c o u n t b a l a n c e ( c o n s t i n t& newBalance ) { a c c o u n t b a l a n c e = newBalance ; } int get balance () { return account balance ;} //@ }; i n t main ( ) { try { i n t amount1 ( 1000) , amount2 ( 2 0 0 ) ; Account a c c o u n t 1 ( amount1 ) ; Account a c c o u n t 2 ( amount2 ) ; // Test a c c o u n t 1 c o u t << a c c o u n t 1 Balance i s : << a c c o u n t 1 . g e t b a l a n c e ( ) << \ n ; // Test a c c o u n t 2 c o u t << a c c o u n t 2 Balance i s : << a c c o u n t 2 . g e t b a l a n c e ( ) << \ n ; account2 . debit (100) ; c o u t << a f t e r d e b i t a c c o u n t 2 new Balance i s : << a c c o u n t 2 . g e t b a l a n c e ( ) << \ n ; account2 . c r e d i t (275) ; c o u t << a f t e r c r e d i t a c c o u n t 2 new Balance i s : << a c c o u n t 2 . g e t b a l a n c e ( ) << \ n ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

17

19

21

23

25

27

29

31

33

35

6.

Exercise 6 (3.13 in book)

(Invoice Class) Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as data membersa part number (type string), a part description (type string), a quantity of the item being purchased (type int) and a price per item (type int). [Note: In subsequent chapters, well use numbers that 8

contain decimal points (e.g., 2.75)called oating-point valuesto represent dollar amounts.] Your class should have a constructor that initializes the four data members. Provide a set and a get function for each data member. In addition, provide a member function named getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as an int value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0. Write a test program that demonstrates class Invoices capabilities. class implemented inline.
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> #i n c l u d e < s t r i n g > u s i n g namespace s t d ; u s i n g namespace QuantLib ; class Invoice { private : s t r i n g part number , p a r t d e s c r i p t i o n ; i n t Quantity , P r i c e ; void v a l i d a t e ( ) { i f ( Quantity < 0 ) { Quantity = 0 ; } e l s e i f ( Price < 0) { Price = 0;} } public : I n v o i c e ( c o n s t s t r i n g& part number , c o n s t s t r i n g& p a r t d e s c r i p t i o n , c o n s t i n t& Quantity , c o n s t i n t& P r i c e ) : part number ( p a r t n u m b e r ) , p a r t d e s c r i p t i o n ( p a r t d e s c r i p t i o n ) , Quantity ( Q u a n t i t y ) , P r i c e ( P r i c e ) { v a l i d a t e ( ) ; } //@ // G e t t e r s s t r i n g get partNumber ( ) { r e t u r n part number ; } string get partDescription () { return part description ;} i n t g e t Q u a n t i t y ( ) { r e t u r n Quantity ; } int get Price () { return Price ;} i n t g e t I n v o i c e A m o u n t ( ) { r e t u r n P r i c e Quantity ; } // S e t t e r s v o i d set partNumber ( c o n s t s t r i n g& new PartNumber ) { part number = new PartNumber ;} v o i d s e t p a r t D e s c r i p t i o n ( c o n s t s t r i n g& n e w P a r t D e s c r i p t i o n ) { p a r t d e s c r i p t i o n = new PartDescription ;} v o i d s e t Q u a n t i t y ( c o n s t i n t& new Quantity ) { Quantity = new Quantity ; } v o i d s e t P r i c e ( c o n s t i n t& n e w P r i c e ) { P r i c e = n e w P r i c e ; } //@ };

10

12

14

16

18

20

22

24

26

28

30

32

34

36

i n t main ( ) { try { I n v o i c e i n v o i c e 1 ( S02345R , Milk 1 L i t t e r , 1 2 , 2 ) ; I n v o i c e i n v o i c e 2 ( S02345R , Milk 1 L i t t e r , 10, 2 ) ; // Test i n v o i c e 1 c o u t << I n v o i c e 1 t e s t \ n ; c o u t << PartNumber : << i n v o i c e 1 . get partNumber ( ) << e n d l ; c o u t << P a r t D e s c r i p t i o n : << i n v o i c e 1 . g e t p a r t D e s c r i p t i o n ( ) << e n d l ; c o u t << P r i c e : << i n v o i c e 1 . g e t P r i c e ( ) << e n d l ; c o u t << Quantity : << i n v o i c e 1 . g e t Q u a n t i t y ( ) << e n d l ; c o u t << InvoiceAmount << i n v o i c e 1 . g e t I n v o i c e A m o u n t ( ) << e n d l ; c o u t << \ n \ n ; // Test i n v o i c e 1 c o u t << I n v o i c e 2 t e s t \ n ; c o u t << PartNumber : << i n v o i c e 2 . get partNumber ( ) << e n d l ; c o u t << P a r t D e s c r i p t i o n : << i n v o i c e 2 . g e t p a r t D e s c r i p t i o n ( ) << e n d l ; c o u t << P r i c e : << i n v o i c e 2 . g e t P r i c e ( ) << e n d l ; c o u t << Quantity : << i n v o i c e 2 . g e t Q u a n t i t y ( ) << e n d l ; c o u t << InvoiceAmount << i n v o i c e 2 . g e t I n v o i c e A m o u n t ( ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

10

12

14

16

18

20

22

24

26

7.

Exercise 7 (3.14 in book)

(Employee Class) Create a class called Employee that includes three pieces of information as data membersa rst name (type string), a last name (type string) and a monthly salary (type int). [Note: In subsequent chapters, well use numbers that contain decimal points (e.g., 2.75)called oatingpoint valuesto represent dollar amounts.] Your class should have a constructor that initializes the three data members. Provide a set and a get function for each data member. If the monthly salary is not positive, set it to 0. Write a test program that demonstrates class Employees capabilities. Create two Employee objects and display each objects yearly salary. Then give each Employee a 10 percent raise and display each Employees yearly salary again. class implemented inline.

10

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> #i n c l u d e < s t r i n g > u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Employee { private : s t r i n g Name , LastName ; i n t Monthly Salary ; void v a l i d a t e ( ) { i f ( Monthly Salary < 0) { Monthly Salary = 0;} } public : Employee ( c o n s t s t r i n g& Name , c o n s t s t r i n g& LastName , c o n s t i n t& M o n t h l y S a l a r y ) : Name( Name ) , LastName ( LastName ) , M o n t h l y S a l a r y ( M o n t h l y S a l a r y ) { validate () ;} //@ // G e t t e r s s t r i n g get Name ( ) { r e t u r n Name ; } s t r i n g get LastName ( ) { r e t u r n LastName ; } i n t get Monthly Salary ( ) { return Monthly Salary ; } // S e t t e r s v o i d set Name ( c o n s t s t r i n g& new Name ) {Name = new Name ; } v o i d s e t L a s t n a m e ( c o n s t s t r i n g& new LastName ) { LastName = new LastName ; } v o i d s e t M o n t h l y S a l a r y ( c o n s t i n t& new MonthlySalary ) { M o n t h l y S a l a r y = new MonthlySalary ; } //@ };

11

13

15

17

19

21

23

25

27

29

31

33

35

i n t main ( ) { try { Employee employee1 ( M a u r i c i o , Bedoya , 1 0 0 ) ; Employee employee2 ( Palermo , Ro dr ig ue z , 1 2 0 ) ; // Test c o u t << c o u t << c o u t << ; employee1 employee1 . get Name ( ) << ; employee1 . get LastName ( ) << ; Annual S a l a r y i s : << 12 employee1 . g e t M o n t h l y S a l a r y ( ) << e n d l

37

39

41

11

employee1 . s e t M o n t h l y S a l a r y ( employee1 . g e t M o n t h l y S a l a r y ( ) 1 . 1 ) ; c o u t << employee1 . get Name ( ) << ; c o u t << employee1 . get LastName ( ) << ; c o u t << New Annual S a l a r y i s : << 12 employee1 . g e t M o n t h l y S a l a r y ( ) << endl ;

// Test c o u t << c o u t << c o u t << ;

employee2 employee2 . get Name ( ) << ; employee2 . get LastName ( ) << ; Annual S a l a r y i s : << 12 employee2 . g e t M o n t h l y S a l a r y ( ) << e n d l

11

13

employee2 . s e t M o n t h l y S a l a r y ( employee2 . g e t M o n t h l y S a l a r y ( ) 1 . 1 ) ; c o u t << employee2 . get Name ( ) << ; c o u t << employee2 . get LastName ( ) << ; c o u t << New Annual S a l a r y i s : << 12 employee2 . g e t M o n t h l y S a l a r y ( ) << endl ; }

15

17

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

19

8.

Exercise 8 (3.15 in book)

(Date Class) Create a class called Date that includes three pieces of information as data members a month (type int), a day (type int) and a year (type int). Your class should have a constructor with three parameters that uses the parameters to initialize the three data members. For the purpose of this exercise, assume that the values provided for the year and day are correct, but ensure that the month value is in the range 112; if it is not, set the month to 1. Provide a set and a get function for each data member. Provide a member function displayDate that displays the month, day and year separated by forward slashes (/). Write a test program that demonstrates class Dates capabilities. QuantLib has a Date class, thats way I implement Date1 (Class implemented inline)
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> #i n c l u d e < s t r i n g > u s i n g namespace s t d ; u s i n g namespace QuantLib ;

12

10

12

14

16

18

20

22

24

26

28

30

32

34

36

38

40

42

44

46

48

c l a s s Date1 { private : i n t Day , Month , Year , MaxYear ; void v a l i d a t e ( ) { set MaxYear ( ) ; i f ( Month<1 | | Month > 12) { c o u t << E r r o r : I n c o r r e c t Month ( S e t Month t o 1 ) \ n ; Month = 1 ; } QL REQUIRE( ( Year<MaxYear ) , E r r o r : Year above MaxYear \ n ) ; QL REQUIRE( Day>=1, E r r o r : Zero o r N e g a t i v e days \ n ) ; // Made a s w i t c h f o r e v a l u a t e days i n month ( i g n o r e l e a p y e a r ) s w i t c h ( Month ) { case 1: QL REQUIRE( Day<=31, January have 31 days \ n ) ; break ; case 2: QL REQUIRE( Day<=28, February have 28 days \ n ) ; case 3: QL REQUIRE( Day<=31, March have 31 days \ n ) ; break ; case 4: QL REQUIRE( Day<=30, A p r i l have 30 days \ n ) ; case 5: QL REQUIRE( Day<=31, May have 31 days \ n ) ; break ; case 6: QL REQUIRE( Day<=30, June have 30 days \ n ) ; case 7: QL REQUIRE( Day<=31, J u l y have 31 days \ n ) ; break ; case 8: QL REQUIRE( Day<=31, August have 31 days \ n ) ; case 9: QL REQUIRE( Day<=30, September have 30 days \ n ) ; break ; case 10: QL REQUIRE( Day<=31, October have 31 days \ n ) ; case 11: QL REQUIRE( Day<=30, November have 30 days \ n ) ; break ; case 12: QL REQUIRE( Day<=31, December have 31 days \ n ) ; default : break ; } }

13

public : Date1 ( c o n s t i n t& Day , c o n s t i n t& Month , c o n s t i n t& Year ) : Day ( Day ) , Month ( Month ) , Year ( Year ) { v a l i d a t e ( ) ; } //@ // G e t t e r s i n t get Day ( ) { r e t u r n Day ; } i n t get Month ( ) { r e t u r n Month ; } i n t g e t Y e a r ( ) { r e t u r n Year ; } // S e t t e r s v o i d s e t D a y ( c o n s t i n t& new Day ) { Day = new Day ; } v o i d set Month ( c o n s t i n t& new Month ) { Month = new Month ; } v o i d s e t Y e a r ( c o n s t i n t& new Year ) { Year = new Year ; } v o i d set MaxYear ( ) { MaxYear = 2 1 0 0 ; } void DisplayDate ( ) { c o u t << Day << / << Month << / << Year << e n d l ; } //@ };

11

13

15

17

19

21

23

i n t main ( ) { try { Date1 d a t e 1 ( 2 2 , 2 3 , 2 0 1 4 ) ; Date1 d a t e 2 ( 1 3 , 1 1 , 2 0 1 5 ) ; // Test d a t e 1 date1 . DisplayDate ( ) ; c o u t << d a t e 1 Day : << d a t e 1 . get Day ( ) << e n d l ; c o u t << d a t e 1 Month : << d a t e 1 . get Month ( ) << e n d l ; c o u t << d a t e 1 Year : << d a t e 1 . g e t Y e a r ( ) << e n d l ; c o u t << \ n \ n ; // Test d a t e 2 date2 . DisplayDate ( ) ; c o u t << d a t e 2 Day : << d a t e 2 . get Day ( ) << e n d l ; c o u t << d a t e 2 Month : << d a t e 2 . get Month ( ) << e n d l ; c o u t << d a t e 2 Year : << d a t e 2 . g e t Y e a r ( ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

25

27

29

31

33

35

37

39

41

43

14

9.

Exercise 9 (4.13 in book)


Read. PseudoCode and tod-down, stepwise renement. PseudoCode -Track several tankful of gasoline. - Recording miles driven. - Recording gallons used. - Calculate the miles per gallon obtained for each tankful. - Display the miles per gallon obtained for each tankful. - Calculate the combined miles per gallon obtained for all tankfuls up to this point. - Display the combined miles per gallon obtained for all tankfuls up to this point. Stepwise renement - Initialize miles, gallons, new miles, new gallons to zero (type integer). - Initialize MPG this tank and Total MPG to zero (type double). - While new milles is dierent than -1: Promt the user enter miles used and set new gallons. Assert if new gallons is zero. If this is the case, terminate the program. If not, continue. Increase gallons by new gallons and miles by new miles. Print MPG this tank. Print Total MPG. C++ code and test (just run the program ) perform below.

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { / I n i t i a l i z e / int miles = 0; int gallons = 0;

11

13

15

i n t new miles = 0; int new gallons = 0; d o u b l e MPG this tank = 0 ; d o u b l e Total MPG = 0 ; / Msg + l o o p / c o u t << Enter t h e m i l e s used ( 1 t o q u i t ) : ; c i n >> n e w m i l e s ; w h i l e ( n e w m i l e s != 1) { m i l e s += n e w m i l e s ; c o u t << Enter g a l o n s : ; c i n >> n e w g a l l o n s ; QL REQUIRE( n e w g a l l o n s > 0 , E r r o r : d i v i s i o n by z e r o ) ; g a l l o n s += n e w g a l l o n s ; MPG this tank = s t a t i c c a s t <double >( n e w m i l e s ) / n e w g a l l o n s ; Total MPG = s t a t i c c a s t <double >( m i l e s ) / g a l l o n s ; c o u t << MPG t h i s t a n k f u l : << s e t p r e c i s i o n ( 6 ) << f i x e d << MPG this tank << e n d l ; c o u t << T o t a l MPG : << s e t p r e c i s i o n ( 6 ) << f i x e d << Total MPG << e n d l ; c o u t << \ n ; c o u t << Enter t h e m i l e s used ( 1 t o q u i t ) : ; c i n >> n e w m i l e s ; } } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

11

13

15

17

19

21

23

25

27

29

31

10.

Exercise 10 (5.5 in book)

Write a program that uses a for statement to sum a sequence of integers. Assume that the rst integer read species the number of values remaining to be entered. Your program should read only one value per input statement. A typical input sequence might be: 5 100 200 300 400 500 where the 5 indicates that the subsequent 5 values are to be summed. (Implemented with while, you do it with for). Pseudo Code - Sum sequence of integer. - First integer species number of values. 16

- Read only one value per input statement. Stepwise renement (You do it) C++ code.
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { / Data t o u s e I n i t i a l i z e d / i n t data num , number ; i n t Suma ( 0 ) ,N( 0 ) ; / Algo h e r e / c o u t << Number o f v a l u e s t o e n t e r : ; c i n >> data num ; w h i l e (N != data num ) { c o u t << New data : ; c i n >> number ; Suma += number ; N++; } c o u t << Suma i s : << Suma ; }

10

12

14

16

18

20

22

24

26

28

30

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

32

11.

Exercise 11 (5.6 in book)

Write a program that uses a for statement to calculate and print the average of several integers. Assume the last value read is the sentinel 9999. A typical input sequence might be 10 8 11 7 9 9999 indicating that the program should calculate the average of all the values preceding 9999.

17

Pseudo Code - Calculate average of several integers. - Print result. C++ code.
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { / Data t o u s e I n i t i a l i z e d / i n t data num , number ; i n t Suma ( 0 ) ; / Algo h e r e / c o u t << Number o f v a l u e s t o e n t e r : ; c i n >> data num ; f o r ( i n t N = 0 ; N != data num ; N++) { c o u t << New data : ; c i n >> number ; Suma += number ; } c o u t << L a s t d a t a : << 9999 << e n d l ; c o u t << Average i s : << s t a t i c c a s t <double >(Suma) / data num ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

10

12

14

16

18

20

22

24

26

28

30

12.

Exercise 12 (5.8 in book)

Write a program that uses a for statement to nd the smallest of several integers. Assume that the rst value read species the number of values remaining and that the rst number is not one of the integers to compare.

18

Pseudo Code - First value species number of integer values. - Prompt message to capture data. - Find the smallest of number of integers. - Print small number . C++ code.
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { / I f v e c t o r c o n t a i n e r , j u s t s o r t / / Data t o u s e I n i t i a l i z e d / i n t data num , data1 , s m a l l e r ; / Algo h e r e / c o u t << Number o f v a l u e s t o e n t e r : ; c i n >> data num ; c o u t << New data : ; c i n >> s m a l l e r ; f o r ( i n t N = 0 ; N != data num 1; N++) { c o u t << New data : ; c i n >> data1 ; ( s m a l l e r >data1 ) ? s m a l l e r=data1 : s m a l l e r ; } c o u t << S m a l l e r data i s : << s m a l l e r ;

11

13

15

17

19

21

23

25

27

29

} c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

31

33

13.

Exercise 13 (5.9 in book)

Write a program that uses a for statement to calculate and print the product of the odd integers from 1 to 15. 19

C++ Code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { c o u t << Odd data from 1 t o 15 a r e : ; f o r ( i n t N = 1 ; N <= 1 5 ;N = N+2) { c o u t << N << setw ( 3 ) ; } } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

10

12

14

16

18

20

14.

Exercise 14 (5.10 in book)

The factorial function is used frequently in probability problems. Using the denition of factorial in Exercise 4.35, write a program that uses a for statement to evaluate the factorials of the integers from 1 to 5. Print the results in tabular format. C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { int Factorial ; c o u t << F a c t o r i a l Number \ n ;

10

20

f o r ( i n t i = 1 ; i <= 5 ; i ++) { Factorial = 1; f o r ( i n t N = 1 ; N <= i ; N++) { F a c t o r i a l =N; } c o u t << i << F a c t o r i a l i s : << F a c t o r i a l << e n d l ; } }

11

13

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

15

15.

Exercise 15 (5.13 in book)

One interesting application of computers is the drawing of graphs and bar charts. Write a program that reads ve numbers (each between 1 and 30). Assume that the user enters only valid values. For each number that is read, your program should print a line containing that number of adjacent asterisks. For example, if your program reads the number 7, it should print *******. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { i n t number ; f o r ( i n t i = 1 ; i <= 5 ; i ++) { c o u t << S e t a number : ; c i n >> number ; QL REQUIRE( ( number>=1 && number <=30) , I n c o r r e c t number p r o v i d e d . ) ; c o u t << > ; f o r ( i n t j = 1 ; j <= number ; j ++) { c o u t << ; } c o u t << e n d l ;

11

13

15

17

19

21

21

} }

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

16.

Exercise 16 (5.14 in book)

A mail order house sells ve dierent products whose retail prices are: product 1 $2.98, product 2 $4.50, product 3 $9.98, product 4 $4.49 and product 5 $6.87. Write a program that reads a series of pairs of numbers as follows: 1. product number. 2. quantity sold. Your program should use a switch statement to determine the retail price for each product. Your program should calculate and display the total retail value of all products sold. Use a sentinelcontrolled loop to determine when the program should stop looping and display the nal results. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t product , q u a n t i t y ; double Total ( 0 . 0 ) , p r i c e ; i n t main ( ) { try { w h i l e ( p r o d u c t != 1) { c o u t << Mail o r d e r s t a r t , s e l e c t a p r o d u c t ( 1 , 2 , 3 , 4 , 5 , 1 f o r Quit ) : ; c i n >> p r o d u c t ;

11

13

15

22

10

i f ( ! c l o s e ( product , 1) ) { c o u t << D i f i n e a q u a n t i t y : ; c i n >> q u a n t i t y ; } switch ( product ) { case 1: price = 2.98; break ; case 2: price = 4.5; break ; case 3: price = 9.98; break ; case 4: price = 4.49; break ; case 5: price = 6.87; break ; default : price = 0; break ; } T o t a l += p r i c e q u a n t i t y ; } c o u t << T o t a l s o l d : << T o t a l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

12

14

16

18

20

22

24

26

28

30

32

34

36

38

40

17.

Exercise 17 (5.19 in book)


4 4 4 4 4 + + + .... 3 5 7 9 11 23

Calculate the value of p from the innite series =4 (1)

Print a table that shows the approximate value of p after each of the rst 1,000 terms of this series. C++ code
#i n c l u d e < i o s t r e a m > #i n c l u d e <cmath> #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; d o u b l e data ( 4 . 0 ) , Pi ( data ) ; // For S e r i e d o u b l e j ( 1) , k ( 1 ) ; // For e x p o n e n t i a l i n t main ( ) { try { f o r ( i n t i = 3 ; i < =1000; i = i +2) { Pi += ( data / i ) pow ( j , k ) ; k++; c o u t << Pi Approximation : << Pi << e n d l ; }
22

10

12

14

16

18

20

} c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

24

26

28

18.

Exercise 18 (6.12 in book)

A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that calculates and prints the parking charges for each of three customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterdays receipts. The program should use the function calculateCharges to determine the charge for each customer. Your outputs should appear in the following format:

24

Car 1 2 3 Total

Hours 1.5 4.0 24.0 29.5

Charge 2.00 2.5 10.0 14.5

From now on, I will start using some tool that can be found in Boost. C++ code
#i n c l u d e #i n c l u d e #i n c l u d e #i n c l u d e <i o s t r e a m > <v e c t o r > < b o o s t / format . hpp> < q l / q u a n t l i b . hpp>

u s i n g namespace s t d ; u s i n g namespace QuantLib ; // L e f t a l i g n e d s t r i n g l i t e r a l Format b o o s t : : format FORMAT( % 6s % 6s % 6s \ n ) ; c l a s s Garage { private : Real Fee1 , Fee2 , Fee3 ; Real Hours ; void v a l i d a t e ( ) { QL REQUIRE( Hours <=24, E r r o r : Cars no Park more than 24 h o u r s . \ n ) ; Fee1 = 2 ; Fee2 = 0 . 5 ; Fee3 = 1 0 . 0 ; } public : Garage ( c o n s t Real& Hours ) : Hours ( Hours ) { v a l i d a t e ( ) ; } v i r t u a l Garage ( ) {} //@ Real c a l c u l a t e C h a r g e s ( ) { i f ( Hours < =3.0) { r e t u r n Fee1 ; } e l s e i f ( 3 . 0 < Hours && 2 4 . 0 > Hours ) { r e t u r n Fee1 + Fee2 ( Hours 3 . 0 ) ; } else { r e t u r n Fee3 ; }

10

12

14

16

18

20

22

24

26

28

30

32

34

36

38

40

25

}
2

Real g e t h o u r s ( ) { r e t u r n Hours ; } //@ };

10

12

14

// G l o b a l f u n c t i o n s Real TotalGarage ( v e c t o r <Garage>& Y e s t e r d a y G a r a g e ) { Real T o t a l = 0 ; f o r ( auto i = 0 ; i != Y e s t e r d a y G a r a g e . s i z e ( ) ; ++i ) { T o t a l += Y e s t e r d a y G a r a g e [ i ] . c a l c u l a t e C h a r g e s ( ) ; } return Total ; }

16

18

20

22

24

Real TotalHours ( v e c t o r <Garage>& Y e s t e r d a y G a r a g e ) { Real T o t a l = 0 ; f o r ( auto i = 0 ; i != Y e s t e r d a y G a r a g e . s i z e ( ) ; ++i ) { T o t a l += Y e s t e r d a y G a r a g e [ i ] . g e t h o u r s ( ) ; } return Total ;

26

28

} i n t main ( ) { try { Garage Car1 ( 1 . 5 ) ; Garage Car2 ( 4 . 0 ) ; Garage Car3 ( 2 4 . 0 ) ; v e c t o r <Garage > Y e s t e r d a y C a r s ; Y e s t e r d a y C a r s . push back ( Car1 ) ; Y e s t e r d a y C a r s . push back ( Car2 ) ; Y e s t e r d a y C a r s . push back ( Car3 ) ; c o u t << FORMAT % Car % Hours % Charge ; f o r ( i n t i= 0 ; i != Y e s t e r d a y C a r s . s i z e ( ) ; ++i ) { c o u t << FORMAT % ( i +1) % Y e s t e r d a y C a r s [ i ] . g e t h o u r s ( ) % Y e s t e r d a y C a r s [ i ] . calculateCharges () ; } c o u t << FORMAT % T o t a l % TotalHours ( Y e s t e r d a y C a r s ) % TotalGarage ( Yesterday Cars ) ;

30

32

34

36

38

40

42

44

46

26

} c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

19.

Exercise 19 (6 13 in book)

An application of function oor is rounding a value to the nearest integer. The statement y = f loor(x + ,5); (2)

rounds the number x to the nearest integer and assigns the result to y. Write a program that reads several numbers and uses the preceding statement to round each of these numbers to the nearest integer. For each number processed, print both the original number and the rounded number. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < b o o s t / format . hpp> #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // L e f t a l l i g n e d s t r i n g l i t e r a l format b o o s t : : format FORMAT( % 10 s % 6s % 10 s % 6s \ n ) ; // G l o b a l f u n c t i o n s v o i d F l o o r F u n c t i o n T e s t ( c o n s t Real& number ) { Real y = f l o o r ( number ) ; c o u t << FORMAT % O r i g i n a l data : % number % New data : % y ; } i n t main ( ) { try { c o u t << T e s t i n g f l o o r f u n c t i o n ;

11

13

15

17

19

21

27

Real number1 ( 3 . 1 4 1 5 ) , number2 ( 5 . 9 8 7 2 ) , number3 ( 1 9 . 2 7 6 ) ;


2

F l o o r F u n c t i o n T e s t ( number1 ) ; F l o o r F u n c t i o n T e s t ( number2 ) ; F l o o r F u n c t i o n T e s t ( number3 ) ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

10

12

20.

Exercise 20 (6.14 in book)


y = f loor(x 10 + ,5)/10;

Function oor can be used to round a number to a specic decimal place. The statement (3)

rounds x to the tenths position (the rst position to the right of the decimal point). The statement y = f loor(x 100 + ,5)/100; (4)

rounds x to the hundredths position (the second position to the right of the decimal point). Write a program that denes four functions to round a number x in various ways: 1. roundToInteger( number ) 2. roundToTenths( number ) 3. roundToHundredths( number ) 4. roundToThousandths( number ) For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.

28

C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < b o o s t / format . hpp> #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // L e f t a l l i g n e d s t r i n g l i t e r a l format b o o s t : : format FORMAT( % 7s % 1s % 7s % 2s % 7s % 3s % 7s % 4s \ n \ n ) ; // G l o b a l f u n c t i o n s Real r o u n d T o I n t e g e r ( c o n s t Real& number ) { Real y = f l o o r ( number ) ; return y ; }

10

12

14

16

18

20

Real roundToTenths ( c o n s t Real& number ) { Real y = f l o o r ( number 10 + 0 . 5 ) / 1 0 ; return y ;

22

24

} Real roundToHundredths ( c o n s t Real& number ) { Real y = f l o o r ( number 100 + 0 . 5 ) / 1 0 0 ; return y ; }

26

28

30

32

34

Real roundToThousandths ( c o n s t Real& number ) { Real y = f l o o r ( number 1000 + 0 . 5 ) / 1 0 0 0 ; return y ;

36

38

} v o i d p r i n t f l o o r ( c o n s t Real& number ) { c o u t << O r i g i n a l data : << number << e n d l ; c o u t << FORMAT % To I n t e g e r : % r o u n d T o I n t e g e r ( number ) % To Thenths : % roundToTenths ( number ) % To Hundredths : % roundToHundredths ( number ) % To Thousandths : % roundToThousandths ( number ) ; }

40

42

44

29

i n t main ( ) { try { c o u t << T e s t i n g f l o o r f u n c t i o n \ n ; Real number1 ( 3 . 1 4 1 5 ) , number2 ( 5 . 9 8 7 2 ) , number3 ( 1 9 . 2 7 6 ) ; p r i n t f l o o r ( number1 ) ; p r i n t f l o o r ( number2 ) ; p r i n t f l o o r ( number3 ) ; }

11

13

15

17

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

21.

Exercise 21 (6.16 in book)


[1, 2] [1, 100] [0, 9] [1000, 1112] [1] [3, 11]

Write statements that assign random integers to the variable n in the following ranges:

C++ code
2

#i n c l u d e #i n c l u d e #i n c l u d e #i n c l u d e

<i o s t r e a m > <ctime > < b o o s t / format . hpp> < q l / q u a n t l i b . hpp>

u s i n g namespace s t d ; u s i n g namespace QuantLib ;

30

void s e t s e e d ( ) { time t T = clock () ; s r a n d (T) ; } Real P o i n t a ( ) { set seed () ; r e t u r n ( 1 + rand ( ) % 1 ) ; }

11

13

15

Real P o i n t b ( ) { set seed () ; r e t u r n ( 1 + s t d : : rand ( ) % 9 9 ) ;

17

19

} Real P o i n t c ( ) { set seed () ; r e t u r n ( s t d : : rand ( ) % 9 ) ; }

21

23

25

27

29

Real P o i n t d ( ) { set seed () ; r e t u r n ( 1 0 0 0 + s t d : : rand ( ) % 1 1 2 ) ;

31

33

} Real P o i n t e ( ) { set seed () ; r e t u r n ( 1 + s t d : : rand ( ) % 1 ) ; }

35

37

39

41

43

Real P o i n t f ( ) { set seed () ; r e t u r n ( 3 + s t d : : rand ( ) % 9 ) ;

45

47

31

i n t main ( ) { try { // 1 <= n <= 2 c o u t << random between [ 1 , 2 ] : << P o i n t a ( ) << e n d l ; // 1 <= n <= 100 c o u t << random between [ 1 , 1 0 0 ] : << P o i n t b ( ) << e n d l ; // 0 <= n <= 9 c o u t << random between [ 0 , 9 ] : << P o i n t c ( ) << e n d l ; // 1000 <= n <= 1112 c o u t << random between [ 1 0 0 0 , 1 1 1 2 ] : << P o i n t d ( ) << e n d l ; // 1 <= n <= 1 c o u t << random between [ 1 , 1 ] : << P o i n t e ( ) << e n d l ; // 3 <= n <= 11 c o u t << random between [ 3 , 1 1 ] : << P o i n t f ( ) << e n d l ; / To s e e how t o g e n e r a t e random numbers with boost , v i s i t : h t t p : / / b l a c k s c h o l e s c o d i g o c p l u s p l u s . b l o g s p o t . com . e s /2014/03/ boost randomnumberexamples . html and b o o s t l i b r a r y . / } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

11

13

15

17

19

21

23

25

27

29

31

22.

Exercise 22 (6.18 in book)


baseexponent

Write a function integerPower ( base, exponent ) that returns the value of

For example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer and that base is an integer. The function integerPower should use for or while to control the calculation. Do not use any math library functions.

32

C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ;

11

13

15

// G l o b a l f u n c t i o n s i n t i n t e g e r P o w e r ( c o n s t i n t& base , c o n s t i n t& exponent ) { int Result = 1; f o r ( i n t i = 0 ; i != exponent ; i ++) { R e s u l t = b a s e ; } return Result ; } i n t main ( ) { try { c o u t << i n t e g e r P o w e r ( 2 , 2 ) ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

17

19

21

23

25

27

29

31

23.

Exercise 22 (6.20 in book)

Write a function multiple that determines for a pair of integers whether the second is a multiple of the rst. The function should take two integer arguments and return true if the second is a multiple of the rst, false otherwise. Use this function in a program that inputs a series of pairs of integers.

33

C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < b o o s t / format . hpp> #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // L e f t a l l i g n e d s t r i n g l i t e r a l format b o o s t : : format FORMAT( % 7s % 1s % 7s % 2s % 7s % 3s % 7s % 4s \ n \ n ) ; // G l o b a l f u n c t i o n s b o o l m u l t i p l e ( c o n s t i n t& data1 , c o n s t i n t& data2 ) { i n t module = data1 % data2 ; bool Result ; c l o s e ( module , 0 ) ? R e s u l t = 1 : R e s u l t = 0 ;

10

12

14

16

18

return Result ;
20

}
22

24

26

28

i n t main ( ) { try { c o u t << m u l t i p l e ( 3 , 2 ) ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

30

32

34

24.

Exercise 23 (6.29 in book)

(Perfect Numbers) An integer is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a function perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the factors of each perfect number to conrm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000.

34

C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l f u n c t i o n s b o o l p e r f e c t ( c o n s t i n t& data1 ) { b o o l R e s u l t = 0 ; // F a l s e i n i t i a l i z a t i o n i n t number = 0 ; f o r ( i n t i = 0 ; i != data1 ; i ++) { number += i ; i f ( number <= data1 ) { c l o s e ( number , data1 ) ? R e s u l t =1: R e s u l t =0; } } return Result ; }

10

12

14

16

18

20

22

24

26

28

30

32

i n t main ( ) { try { f o r ( i n t i = 0 ; i <= 1 0 0 0 ; i ++) { c l o s e ( p e r f e c t ( i ) , 1 ) ? c o u t << i << i s p e r f e c t \ n : ; } } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

34

36

38

25.

Exercise 24 (6.31 in book)

(Reverse Digits) Write a function that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the function should return 1367.

35

C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l f u n c t i o n s i n t r e v e r s e ( c o n s t i n t& number ) { i n t i n v ( 0 ) ,num( number ) ; w h i l e (num >0) { i n v = i n v 10 + (num %10) ; num = num/ 1 0 ; } return inv ; }

11

13

15

17

19

21

23

25

i n t main ( ) { try { i n t number = 7 6 1 3 ; i n t rev number = r e v e r s e ( number ) ; c o u t << O r i g i n i a l Number : << number << e n d l ; c o u t << R e v e r s e Number : << rev number << e n d l ; }

27

29

31

33

35

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

26.

Exercise 25 (6.34 in book)

Write a program that simulates coin tossing. For each toss of the coin, the program should print Heads or Tails. Let the program toss the coin 100 times and count the number of times each side of the coin appears. Print the results. The program should call a separate function ip that takes no arguments and returns 0 for tails and 1 for heads. [Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time.] 36

C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l f u n c t i o n s int f l i p () { time t T = clock () ; s r a n d (T) ; r e t u r n 0 + rand ( ) %2; }

10

12

14

16

18

20

22

24

26

i n t main ( ) { try { i n t T a i l s ( 0 ) , Heads ( 0 ) ; f o r ( i n t i = 1 ; i <= 1 0 0 0 ; i ++) { int a = f l i p () ; c l o s e ( a , 0 ) ? T a i l s +=1:Heads+=1; } c o u t << T a i l s : << T a i l s << e n d l ; c o u t << Heads : << Heads ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

28

30

32

34

36

27.

Exercise 26 (6.35 in book)

(Computers in Education) Computers are playing an increasing role in education. Write a program that helps an elementary school student learn multiplication. Use rand to produce two positive one-digit integers. It should then type a question such as

37

How much is 6 times 7? The student then types the answer. Your program checks the students answer. If it is correct, print Very good!, then ask another multiplication question. If the answer is wrong, print No. Please try again., then let the student try the same question repeatedly until the student nally gets it right. C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l f u n c t i o n s i n t number ( ) { time t T = clock () ; s r a n d (T) ; r e t u r n 1 + rand ( ) %9; }

10

12

14

16

18

20

22

void M u l t i p l i c a t i o n ( ) { i n t data1 = number ( ) ; i n t data2 = number ( ) ; i n t r e s u l t = data1 data2 ; int user result ; c o u t << How much i s <<data1 << t i m e s << data2 << ? : ; c i n >> u s e r r e s u l t ; w h i l e ( u s e r r e s u l t != r e s u l t ) { c o u t << No . P l e a s e t r y a g a i n : ; c i n >> u s e r r e s u l t ; } c o u t << Very good ; }

24

26

28

30

32

34

36

38

40

i n t main ( ) { try { Multiplication () ; }

38

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

28.

Exercise 27 (6.37 in book)

More sophisticated computer-aided instruction systems monitor the students performance over a period of time. The decision to begin a new topic often is based on the students success with previous topics. Modify the program of Exercise 6.36 to count the number of correct and incorrect responses typed by the student. After the student types 10 answers, your program should calculate the percentage of correct responses. If the percentage is lower than 75 percent, your program should print Please ask your instructor for extra help.and terminate (Base exercise will be 6.35, not 6.36). C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l v a r i a b l e i n t bad answers (0) ; // G l o b a l f u n c t i o n s i n t number ( ) { time t T = clock () ; s r a n d (T) ; r e t u r n 1 + rand ( ) %9; }

11

13

15

17

19

21

23

25

void M u l t i p l i c a t i o n ( ) { i n t data1 = number ( ) ; i n t data2 = number ( ) ; i n t r e s u l t = data1 data2 ; int user result ;

39

c o u t << How much i s <<data1 << t i m e s << data2 << ? : ; c i n >> u s e r r e s u l t ; w h i l e ( u s e r r e s u l t != r e s u l t ) { c o u t << No . P l e a s e t r y a g a i n : ; b a d a n s w e r s += 1 ; c i n >> u s e r r e s u l t ; } c o u t << Very good \ n ; } v o i d M u l t i p l i c a t i o n T e s t ( c o n s t i n t& n u m b e r o f q u e s t i o n s ) { f o r ( i n t i = 0 ; i != n u m b e r o f q u e s t i o n s ; ++i ) { Multiplication () ; } // S t a t i s t i c s d o u b l e e v a l = s t a t i c c a s t <double >( b a d a n s w e r s ) / n u m b e r o f q u e s t i o n s ; ( e v a l >= 0 . 2 5 ) ? c o u t << P l e a s e ask your i n s t r u c t o r f o r e x t r a h e l p : ; } i n t main ( ) { try { Multiplication Test (3) ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

11

13

15

17

19

21

23

25

27

29

31

33

35

29.

Exercise 28 (6.48 in book)

Write function distance that calculates the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double.

40

C++ code
#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s point { private : double X , Y ; public : p o i n t ( c o n s t d o u b l e& X, c o n s t d o u b l e& Y) : X (X) , Y (Y) {} //@ d o u b l e get X ( ) { r e t u r n X ; } d o u b l e get Y ( ) { r e t u r n Y ; } //@ }; // G l o b a l f u n c t i o n s d o u b l e p o i n t d i s t a n c e ( p o i n t& p1 , p o i n t& p2 ) { d o u b l e x d i s t a n c e = p2 . get X ( ) p1 . get X ( ) ; d o u b l e y d i s t a n c e = p2 . get Y ( ) p1 . get Y ( ) ; return sqrt ( x distance x distance + y distance y distance ) ;
26

10

12

14

16

18

20

22

24

28

30

32

34

i n t main ( ) { try { p o i n t A( 2 , 3) ; p o i n t B( 4 ,4) ; c o u t << Po in t d i s t a n c e i s : << p o i n t d i s t a n c e (A, B) ; }

36

38

40

42

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

41

30.

Exercise 29 (6.59 in book)

Write a program that uses a function template called max to determine the largest of three arguments. Test the program using integer, character and oating-point number arguments. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l f u n c t i o n s template <typename T> T min ( c o n s t T& num1 , c o n s t T& num2) { T solution ; (num1>=num2) ? s o l u t i o n = num2 : s o l u t i o n = num1 ;

11

13

15

return solution ;
17

19

21

23

25

i n t main ( ) { try { c o u t << Min number ( i n t ) i s : << min <i n t > (2 ,3) << e n d l ; c o u t << Min number ( d o u b l e ) i s : << min <double > ( 4 . 5 6 , 2 . 3 3 ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

27

29

31

33

31.

Exercise 30 (7.10 in book)

Use a one-dimensional array to solve the following problem. A company pays its salespeople on a commission basis. The salespeople each receive $200 per week plus 9 percent of their gross sales for that week. For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9 42

percent of $5000, or a total of $650. Write a program (using an array of counters) that determines how many of the salespeople earned salaries in each of the following ranges (assume that each salespersons salary is truncated to an integer amount): 200 - 299. 300 - 399. 400 - 499. 500 - 599. 600 - 699. 700 - 799. 800 - 899. 900 - 999. 1000 - and over. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { const int frequency size (9) ; const int s a l e s s i z e (5) ; c o n s t s t r i n g s a l a r y r a n g e [ f r e q u e n c y s i z e ] ={ [200 299] , [300 399] , [400 499] , [500 599] , [600 699] , [700 799] , [800 899] , [900 999] , [ 1 0 0 0 , / infty ] }; int Sales [ s a l e s s i z e ] = {5000 ,5000 ,2000 ,1500 ,7000}; i n t Frequency [ f r e q u e n c y s i z e ] = { 0 } ; int worker salary [ s a l e s s i z e ] ; f o r ( i n t i = 0 ; i < s a l e s s i z e ; i ++) { w o r k e r s a l a r y [ i ] = 200 + S a l e s [ i ] 0 . 0 9 ; c o u t << s a l a r y << i << : << w o r k e r s a l a r y [ i ] << e n d l ;

11

13

15

17

19

21

43

11

13

15

17

19

21

23

25

27

29

31

33

35

i f ( w o r k e r s a l a r y [ i ] >= 200 && w o r k e r s a l a r y [ i ] < 3 0 0 ) { Frequency [ 0 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 400) { Frequency [ 1 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 500) { Frequency [ 2 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 600) { Frequency [ 3 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 700) { Frequency [ 4 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 800) { Frequency [ 5 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 900) { Frequency [ 6 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] < 1000) { Frequency [ 7 ] +=1; } e l s e i f ( w o r k e r s a l a r y [ i ] >= 1 0 0 0 ) { Frequency [ 8 ] +=1; } } c o u t << \ n \ n ; c o u t << setw ( 1 0 ) << S a l a r y r a n g e << setw ( 7 ) << Frequency \ n ; f o r ( i n t i = 0 ; i != f r e q u e n c y s i z e ; i ++) { c o u t << setw ( 7 ) << s a l a r y r a n g e [ i ] << setw ( 7 ) << Frequency [ i ] << e n d l ; } }

37

39

41

43

45

44

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

32.

Exercise 31 (7.13 in book)

Write single statements that perform the following one-dimensional array operations: Initialize the 10 elements of integer array counts to zero. Add 1 to each of the 15 elements of integer array bonus. Read 12 values for double array monthlyTemperatures from the keyboard. Print the 5 values of integer array bestScores in column format. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; i n t main ( ) { try { // A) const int size A = 10; i n t arrayA [ s i z e A ] = { 0 } ; // B) const int size B = 15; i n t Bonus [ s i z e B ] = { 2 } ; f o r ( i n t i= 0 ; i != s i z e B ; i ++) { Bonus [ i ]+=1; }

11

13

15

17

19

21

45

// C) c o u t << Po in t C << e n d l ; const int size C = 12; d o u b l e monthlyTemperatures [ s i z e C ] ; f o r ( i n t i = 0 ; i != s i z e C ; i ++) { c o u t << S e t t e m p e r a t u r e f o r month << i +1 << : ; c i n >> monthlyTemperatures [ i ] ; } c o u t << \ n ; // D) c o u t << Po in t C << e n d l ; const int size D = 5; int bestScores [ size D ] = {99 ,100 ,98 ,96 ,90}; f o r ( i n t i = 0 ; i != s i z e D ; i ++) { c o u t << s c o r e i s : << b e s t S c o r e s [ i ] << e n d l ; } } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

11

13

15

17

19

21

23

25

27

29

33.

Exercise 32 (7.15 in book)

Use a one-dimensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate it and store it in the array only if it is not a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Provide for the worst case n which all 20 numbers are dierent. Use the smallest possible array to solve this problem.

46

C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < v e c t o r > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l v a r i a b l e

11

13

15

17

i n t main ( ) { try { const int s i z e = 20; int array [ s i z e ] ; i n t number ; f o r ( i n t i = 0 ; i != s i z e ; i ++) { c o u t << Choose a number between 10 and 1 0 0 : ; c i n >> number ; QL REQUIRE( ( number >=10 && number <=100) , number above ( below ) r a n g e [10 ,100] ) ; a r r a y [ i ] = number ; } c o u t << \ n ; v e c t o r <i n t > u n i q u e d a t a ( s i z e ) ; // Unique r e s u l t copy h e r e

19

21

23

25

27

29

31

// Using some STL a l g o r i t m s v e c t o r <i n t > : : i t e r a t o r i t ; // i t e r a t o r ( c o v e r e d i n f u t u r e c h a p t e r ) i t = s t d : : u n i q u e c o p y ( array , a r r a y + s i z e , u n i q u e d a t a . b e g i n ( ) ) ; u n i q u e d a t a . r e s i z e ( s t d : : d i s t a n c e ( u n i q u e d a t a . b e g i n ( ) , i t ) ) ; // r e s i z e ( ignore zeros ) // P r i n t r e s u l t s c o u t << R e s u l t s a r e : \ n ; f o r ( i n t i = 0 ; i != s i z e ; i ++) { c o u t << u n i q u e d a t a . a t ( i ) << e n d l ; } }

33

35

37

39

41

47

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

34.

Exercise 33 (7.17 in book)

Write a program that simulates the rolling of two dice. The program should use rand to roll the rst die and should use rand again to roll the second die. The sum of the two values should then be calculated. [ Note: Each die can show an integer value from 1 to 6, so the sum of the two values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums.] Figure 7.32 shows the 36 possible combinations of the two dice. Your program should roll the two dice 36,000 times. Use a one-dimensional array to tally the numbers of times each possible sum appears. Print the results in a tabular format. Also, determine if the totals are reasonable (i.e., there are six ways to roll a 7, so approximately one-sixth of all the rolls should be 7). Note Something strange happen when I solve this with xcode 4.5.2. Mi rst attempt was:
1

#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l f u n c t i o n int r o l l () { srand ( ti me t ( c l o c k ( ) ) ) ; r e t u r n 1 + rand ( ) % 6 ; }

11

13

15

17

19

i n t main ( ) { try {

48

const int s i z e = 11; int r o l l p o s i b i l i t i e s [ size ]={2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12}; i n t f r e q u e n c i e s [ s i z e ]={0}; int total (0) ; f o r ( i n t i = 0 ; i != 3 6 0 0 0 ; i ++) { total = r o l l () + r o l l () ; int A = total 2; // Adjustment f r e q u e n c i e s [A]++; }

11

13

15

17

f o r ( i n t i = 0 ; i != s i z e ; i ++) { c o u t << r o l l p o s i b i l i t i e s [ i ] << : << f r e q u e n c i e s [ i ] << e n d l ; } } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

19

21

23

25

However, the frequency distribution did not convince me at all. So, I guess that the problem can be found in roll function (random number generation seed). Then I just change the roll function for:
1

int r o l l () { time t A = clock () ; t i m e t B = rand ( ) c l o c k ( ) ; s r a n d (A+B) ; // More n o i s e h e r e r e t u r n 1 + rand ( ) % 6 ; }

and the result correspond to probability theory expectations (i.e., there are six ways to roll a 7, so approximately one-sixth - 6 / 36 - of all the rolls should be 7).

35.

Exercise 34 (7.20 in book)

( Airline Reservations System) A small airline has just purchased a computer for its new automated reservations system. You have been asked to program the new system. You are to write a 49

program to assign seats on each ight of the airlines only plane (capacity: 10 seats). Your program should display the following menu of alternativesPlease type 1 for First Class.and Please type 2 for .Economy. If the person types 1, your program should assign a seat in the rst class section (seats 1-5). If the person types 2, your program should assign a seat in the economy section (seats 6-10). Your program should print a boarding pass indicating the persons seat number and whether it is in the rst class or economy section of the plane. Use a one-dimensional array to represent the seating chart of the plane. Initialize all the elements of the array to 0 to indicate that all seats are empty. As each seat is assigned, set the corresponding elements of the array to 1 to indicate that the seat is no longer available. Your program should, of course, never assign a seat that has already been assigned. When the rst class section is full, your program should ask the person if it is acceptable to be placed in the economy section (and vice versa). If yes, then make the appropriate seat assignment. If no, then print the message Next ight leaves in 3 hours. C++ code
#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; // G l o b a l v a r i a b l e s int int int int seats [11]={0}; plane class ; FC = 1 ; SC = 6 ;

10

12

14

// G l o b a l f u n c t i o n
16

18

20

22

24

26

28

void assign second ( ) { i f (SC <= 1 0 ) { s e a t s [ SC] = 1 ; SC++; } else { c o u t << Second c l a s s i s f u l l \ n ; } }

50

void a s s i g n f i r s t ( ) { i f (FC <= 5 ) { s e a t s [ FC] = 1 ; FC++; } else { int alternative ; c o u t << F i r s t c l a s s i s f u l l , c o n s i d e r s e c o n d c l a s s ? ( 1 Yes / 0 No) : ; c i n >> a l t e r n a t i v e ; QL REQUIRE( ( a l t e r n a t i v e == 1 | | a l t e r n a t i v e == 0 ) , I n c o r r e c t a l t e r n a t i v e , s t a r t r e s e r v a t i o n again . ) ; i f ( a l t e r n a t i v e == 0 ) { c o u t << Next f l i g h t l e a v e s i n 3 h o u r s ; } else { assign second () ; } } } void as s i gn ( ) { ( close ( plane class ,1) )? a s s i g n f i r s t () : assign second () ; } void Reservation ( ) { c o u t << P l e a s e type 1 f o r F i r s t c l a s s o r type 2 f o r s e c o n d c l a s s : ; c i n >> p l a n e c l a s s ; QL REQUIRE( ( p l a n e c l a s s ==1 | | p l a n e c l a s s == 2 ) , I n c o r r e c t c l a s s \ n ) ; assign () ; } i n t main ( ) { try { Reservation () Reservation () Reservation () Reservation () Reservation () ; ; ; ; ;

10

12

14

16

18

20

22

24

26

28

30

32

34

36

38

40

42

44

46

48

51

Reservation () ; Reservation () ; // P r i n t s t a t e o f s e a t s a f t e r r e s e r v a t i o n . c o u t << \ n \ n ; c o u t << S e a t s s t a t e \ n ; f o r ( i n t i = 1 ; i <= 1 0 ; i ++) { i f ( i <=5) { c o u t << F i s r t c l a s s s e a t : << i << i s ; } else { c o u t << Second c l a s s s e a t : << i << i s ; } c o u t << s e a t s [ i ] << e n d l ; } } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

10

12

14

16

18

20

22

24

26

36.

Exercise 35 (9.4 in book)

(Enhancing Class Time) Provide a constructor that is capable of using the current time from the time() functiondeclared in the C++ Standard Library header ctimeto initialize an object of the Time class. Note: Class implemented inline. Try to separate the content int two les: the .hpp and .cpp le; and compile. C++ code
2

#i n c l u d e < i o s t r e a m > #i n c l u d e <ctime > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ;

52

10

12

14

16

18

c l a s s time1 { private : i n t hour , minutes , s e c o n d s ; v o i d g e t t i m e ( ) // h e l p e r { t i m e t now = s t d : : time ( 0 ) ; s t r u c t tm tmp = l o c a l t i m e (&now ) ; hour = tmp>tm hour ; minutes = tmp>tm min ; s e c o n d s = tmp>t m s e c ; } public : time1 ( ) { g e t t i m e ( ) ; } // Already v a l i d a t e v i r t u a l time1 ( ) {} //@ // G e t t e r s i n t g e t H o u r s ( ) { r e t u r n hour ; } i n t g e t M i n u t e s ( ) { r e t u r n minutes ; } int get Seconds () { return seconds ;} // S e t t e r s v o i d s e t t i m e 1 ( c o n s t i n t& new hour , c o n s t i n t& new minutes , c o n s t i n t& new seconds ) { QL REQUIRE( ( new hour >=0 && new hour <= 2 3 ) , E r r o r : Hour b e l o n g t o r a n g e [0 ,23] ) ; QL REQUIRE( ( new minutes >=0 && new minutes <= 6 0 ) , E r r o r : Hour b e l o n g t o range [ 0 , 2 3 ] ) ; QL REQUIRE( ( new seconds >=0 && n e w s e c o n d s <= 6 0 ) , E r r o r : Hour b e l o n g t o range [ 0 , 2 3 ] ) ; hour = new hour ; minutes = new minutes ; seconds = new seconds ; } //@ }; i n t main ( ) { try { time1 T ; c o u t << Hour i s : << T . g e t H o u r s ( ) << e n d l ; c o u t << Minute i s : << T . g e t M i n u t e s ( ) << e n d l ; c o u t << Second i s : << T . g e t S e c o n d s ( ) << e n d l ; T. s e t t i m e 1 (20 ,34 ,12) ;

20

22

24

26

28

30

32

34

36

38

40

42

44

53

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

37.

Exercise 36 (9.6 in book)

(Rational Class) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of the classthe numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For example, the fraction
2 4

would be stored in the object as 1 in the numerator and 2 in the denominator. Provide public member functions that perform each of the following tasks: 1. Adding two Rational numbers. The result should be stored in reduced form. 2. Subtracting two Rational numbers. The result should be stored in reduced form. 3. Multiplying two Rational numbers. The result should be stored in reduced form. 4. Dividing two Rational numbers. The result should be stored in reduced form. 5. Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator. 6. Printing Rational numbers in oating-point format.

54

C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; class fraction { private : i n t numerator , d e n o m i n a t o r ; public : f r a c t i o n ( c o n s t i n t& numerator = 2 , c o n s t i n t& denominator = 4 ) : numerator ( numerator ) , d e n o m i n a t o r ( denominator ) {} v i r t u a l f r a c t i o n ( ) {} //@ i n t g e t n u m e r a t o r ( ) { r e t u r n numerator ; } i n t get denominator ( ) { return denominator ; } //@ }; class rational { // Composition private : f r a c t i o n da ta 1 , d a t a 2 ; // R e s u l t s i n t numerator , denominator ; public : r a t i o n a l ( c o n s t f r a c t i o n& data1 , c o n s t f r a c t i o n& data2 ) : d a t a 1 ( data1 ) , d a t a 2 ( data2 ) {} v i r t u a l r a t i o n a l ( ) {} //@ v o i d add ( ) { denominator = d a t a 1 . g e t d e n o m i n a t o r ( ) d a t a 2 . g e t d e n o m i n a t o r ( ) ; numerator = ( d a t a 2 . g e t d e n o m i n a t o r ( ) d a t a 1 . g e t n u m e r a t o r ( ) + data1 . get denominator () data2 . get numerator () ) ; } void substract ( ) { denominator = d a t a 1 . g e t d e n o m i n a t o r ( ) d a t a 2 . g e t d e n o m i n a t o r ( ) ; numerator = ( d a t a 2 . g e t d e n o m i n a t o r ( ) d a t a 1 . g e t n u m e r a t o r ( ) data1 . get denominator () data2 . get numerator () ) ; }

11

13

15

17

19

21

23

25

27

29

31

33

35

37

39

41

55

void multiply ( ) { numerator = ( d a t a 1 . g e t n u m e r a t o r ( ) d a t a 2 . g e t n u m e r a t o r ( ) ) ; denominator = d a t a 1 . g e t d e n o m i n a t o r ( ) d a t a 2 . g e t d e n o m i n a t o r ( ) ; } void divide ( ) { numerator = ( d a t a 1 . g e t n u m e r a t o r ( ) d a t a 2 . g e t d e n o m i n a t o r ( ) ) ; denominator = d a t a 1 . g e t d e n o m i n a t o r ( ) d a t a 2 . g e t n u m e r a t o r ( ) ; } void p r i n t r a t i o n a l ( ) { c o u t << F r a c t i o n a l r e s u l t i s : << numerator << / << denominator << e n d l ; } void print double ( ) { c o u t << Double r e s u l t i s : << ( s t a t i c c a s t <double >(numerator ) / denominator ) << e n d l ; } //@ };

10

12

14

16

18

20

22

24

26

28

30

i n t main ( ) { try { // D e f a u l t // f r a c t i o n A, B ; f r a c t i o n A( 2 , 3 ) , B( 1 , 3 ) ; r a t i o n a l Rat (A, B) ; Rat . add ( ) ; c o u t << Add r e s u l t \ n ; Rat . p r i n t r a t i o n a l ( ) ; Rat . p r i n t d o u b l e ( ) ; c o u t << \ n ; c o u t << S u b s t r a c t r e s u l t \ n ; Rat . s u b s t r a c t ( ) ; Rat . p r i n t r a t i o n a l ( ) ; Rat . p r i n t d o u b l e ( ) ; c o u t << \ n ;

// Uncomment t o e v a l u a t e d e f a u l t // Comment f o r e v a l u a t e d e f a u l t

32

34

36

38

40

42

44

56

c o u t << M u l t i p l y r e s u l t \ n ; Rat . m u l t i p l y ( ) ; Rat . p r i n t r a t i o n a l ( ) ; Rat . p r i n t d o u b l e ( ) ; c o u t << \ n ; c o u t << D i v i d e r e s u l t \ n ; Rat . d i v i d e ( ) ; Rat . p r i n t r a t i o n a l ( ) ; Rat . p r i n t d o u b l e ( ) ; c o u t << \ n ; }

10

12

14

16

18

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

38.

Exercise 37 (9.11 in book)

(Rectangle Class) Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide member functions that calculate the perimeter and the area of the rectangle. Also, provide set and get functions for the length and width attributes. The set functions should verify that length and width are each oating-point numbers larger than 0.0 and less than 20.0. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Rectangle { private : Real l e n g t h , w i d t h ; void v a l i d a t e ( ) { QL REQUIRE( ( l e n g t h <= 2 0 . 0 && l e n g t h >=0) , E r r o r : I n c o r r e c t l e n g t h ) ; QL REQUIRE( ( w i d t h <= 2 0 . 0 && w i d t h >=0) , E r r o r : I n c o r r e c t l e n g t h ) ; }

11

13

57

public : R e c t a n g l e ( c o n s t Real& l e n g t h = 1 , c o n s t Real& width = 1 ) : l e n g t h ( l e n g t h ) , w i d t h ( width ) { validate () ;} v i r t u a l R e c t a n g l e ( ) {} // @ Real p e r i m e t e r ( ) { r e t u r n ( l e n g t h Real a r e a ( ) { r e t u r n l e n g t h

+ width ) 2;}

width ; }

10

12

14

16

// S e t t e r v o i d s e t l e n g t h ( c o n s t Real& n e w l e n g t h ) { length = new length ; validate () ; } v o i d s e t w i d t h ( c o n s t Real& new width ) { w i d t h = new width ; validate () ; } // G e t t e r Real g e t l e n g t h ( ) { r e t u r n l e n g t h ; } Real g e t w i d t h ( ) { r e t u r n w i d t h ; } //@ };

18

20

22

24

26

28

30

32

34

36

38

40

i n t main ( ) { try { // R e c t a n g l e R; // D e f a u l t R e c t a n g l e R( 2 , 5 ) ; c o u t << P e r i m e t e r : << R. p e r i m e t e r ( ) << e n d l ; c o u t << Area : << R. a r e a ( ) << e n d l ; c o u t << Length : << R. g e t l e n g t h ( ) << e n d l ; c o u t << Width : << R. g e t w i d t h ( ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

42

44

46

48

58

39.

Exercise 38 (9.12 in book)

(Enhancing Class Rectangle) Create a more sophisticated Rectangle class than the one you created in Exercise 9.11. This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set function that accepts four sets of coordinates and veries that each of these is in the rst quadrant with no single x- or y-coordinate larger than 20.0. The set function also veries that the supplied coordinates do, in fact, specify a rectangle. Provide member functions that calculate the length, width, perimeter and area. The length is the larger of the two dimensions. Include a predicate function square that determines whether the rectangle is a square. C++ code
#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; class coordinate { private : Real X , Y ; void v a l i d a t e ( ) { QL REQUIRE( ( X <= 2 0 . 0 && X >=0) , E r r o r : I n c o r r e c t l e n g t h ) ; QL REQUIRE( ( Y <= 2 0 . 0 && Y >=0) , E r r o r : I n c o r r e c t l e n g t h ) ; } v o i d copy ( c o n s t c o o r d i n a t e& o t h e r ) { X = other . X ; Y = other . Y ; } public : c o o r d i n a t e ( c o n s t Real& X, c o n s t Real& Y) : X (X) , Y (Y) {} c o o r d i n a t e &o p e r a t o r = ( c o n s t c o o r d i n a t e& o t h e r ) { i f (& o t h e r != t h i s ) { copy ( o t h e r ) ; return this ; } else { return this ; } }

10

12

14

16

18

20

22

24

26

28

30

32

34

59

Real get X ( ) { r e t u r n X ; } Real get Y ( ) { r e t u r n Y ; } }; c l a s s Rectangle { private : c o o r d i n a t e C1 , C2 , C3 , C4 ; Real width , l e n g t h ; void v a l i d a t e ( ) { / C 3 C 4 C 1 C 2 /

11

Rectangle corners

13

15

17

Real l e n g t h 1 = C2 . get X ( ) C1 . get X ( ) ; Real l e n g t h 2 = C4 . get X ( ) C3 . get X ( ) ; Real width1 = C3 . get Y ( ) C1 . get Y ( ) ; Real width2 = C4 . get Y ( ) C2 . get Y ( ) ; QL REQUIRE( ( l e n g t h 1 == l e n g t h 2 ) , E r r o r : I s not a s q u a r e ) ; QL REQUIRE( ( width1 == width2 ) , E r r o r : I s not a s q u a r e ) ; length = length1 ; width = width1 ; }

19

21

23

25

27

29

31

public : R e c t a n g l e ( c o n s t c o o r d i n a t e& C1 , c o n s t c o o r d i n a t e& C2 , c o n s t c o o r d i n a t e& C3 , c o n s t c o o r d i n a t e& C4) : C1 (C1) , C2 (C2) , C3 (C3) , C4 (C4) { v a l i d a t e ( ) ; } v i r t u a l R e c t a n g l e ( ) {} // @ Real p e r i m e t e r ( ) { r e t u r n ( l e n g t h + width ) 2 ; } Real a r e a ( ) { r e t u r n l e n g t h width ; } // S e t t e r v o i d s e t C 1 ( c o n s t c o o r d i n a t e& new C1 ) { C1 = new C1 ; } v o i d s e t C 2 ( c o n s t c o o r d i n a t e& new C2 ) { C2 = new C2 ; } v o i d s e t C 3 ( c o n s t c o o r d i n a t e& new C3 ) { C3 = new C3 ; }

33

35

37

39

41

43

45

47

60

v o i d s e t C 4 ( c o n s t c o o r d i n a t e& new C4 ) { C4 = new C4 ; } // G e t t e r c o o r d i n a t e get C1 ( ) { r e t u r n C1 ; } c o o r d i n a t e get C2 ( ) { r e t u r n C2 ; } c o o r d i n a t e get C3 ( ) { r e t u r n C3 ; } c o o r d i n a t e get C4 ( ) { r e t u r n C4 ; } Real g e t l e n g t h ( ) { r e t u r n l e n g t h ; } Real g e t w i d t h ( ) { r e t u r n width ; } //@ };

11

13

15

17

19

21

23

25

i n t main ( ) { try { coordinate coordinate coordinate coordinate

C1 ( 1 , C2 ( 6 , C3 ( 1 , C4 ( 6 ,

0) ; 0) ; 5) ; 5) ;

27

29

31

R e c t a n g l e R( C1 , C2 , C3 , C4) ; c o u t << P e r i m e t e r : << R. p e r i m e t e r ( ) << e n d l ; c o u t << Area : << R. a r e a ( ) << e n d l ; c o u t << Length : << R. g e t l e n g t h ( ) << e n d l ; c o u t << Width : << R. g e t w i d t h ( ) << e n d l ; }

33

35

37

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

40.

Exercise 39 (10.8 in book)

Create a SavingsAccount class. Use a static data member annualInterestRate to store the annual interest rate for each of the savers. Each member of the class contains a private data member savingsBalance indicating the amount the saver currently has on deposit. Provide member function calculateMonthlyInterest that calculates the monthly interest by multiplying the balance by annualInterestRate divided by 12; this interest should be added to savingsBalance. Provide 61

a static member function modifyInterestRate that sets the static annualInterestRate to a new value. Write a driver program to test class SavingsAccount. Instantiate two dierent objects of class SavingsAccount, saver1 and saver2, with balances of 2000,00and3000.00, respectively. Set the annualInterestRate to 3 percent. Then calculate the monthly interest and print the new balances for each of the savers. Then set the annualInterestRate to 4 percent, calculate the next months interest and print the new balances for each of the savers. C++ code
#i n c l u d e < i o s t r e a m > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Savingaccount { private : s t a t i c Real a n n u a l I n t e r e s t R a t e ; Real SavingBalance , m o n t h l y I n t e r e s t ; public : S a v i n g a c c o u n t ( c o n s t Real& b a l a n c e ) : S a v i n g B a l a n c e ( b a l a n c e ) { } v i r t u a l S a v i n g a c c o u n t ( ) {} //@ void calculateMonthlyInterest ( ) { monthlyInterest = SavingBalance ( annualInterestRate / 12) ; S a v i n g B a l a n c e += m o n t h l y I n t e r e s t ; } s t a t i c v o i d m o d i f y I n t e r e s t R a t e ( c o n s t Real& n e w a n n u a l I n t e r e s t R a t e ) { annualInterestRate = new annualInterestRate ;} Real g e t S a v i n g B a l a n c e ( ) { r e t u r n S a v i n g B a l a n c e ; } void print ( ) { c o u t << I n i t i a l Balance : << g e t S a v i n g B a l a n c e ( ) << e n d l ; calculateMonthlyInterest () ; c o u t << Montlhy I n t e r e s t : << m o n t h l y I n t e r e s t << e n d l ; c o u t << New Balanace i s : << S a v i n g B a l a n c e << e n d l ; }
40

10

12

14

16

18

20

22

24

26

28

30

32

34

36

38

};

62

Real S a v i n g a c c o u n t : : a n n u a l I n t e r e s t R a t e = 0 . 0 ;
2

// I n i t i a l i c e f o r a l l o b j e c t s

i n t main ( ) { try { Real r 0 = 0 . 0 3 ; Savingaccount : : modifyInterestRate ( r0 ) ;

// For a l l o b j e c t s S a v i n g a c c o u n t

10

Savingaccount saver1 ( 2 0 0 0 . 0 ) , saver2 ( 3 0 0 0 . 0 ) ;


12

14

saver1 . print () ; c o u t << e n d l ; saver2 . print () ; c o u t << e n d l ; Real r 1 = 0 . 0 4 ; Savingaccount : : modifyInterestRate ( r1 ) ; saver1 . print () ; c o u t << e n d l ; saver2 . print () ; c o u t << e n d l ; }

16

18

20

// For a l l o b j e c t s S a v i n g a c c o u n t

22

24

26

28

30

32

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

From now on, I will implement code following the good programming practice 12.1 (page 655 in book).

41.

Exercise 40 (12.9 in book)

(Package Inheritance Hierarchy) Package-delivery services, such as FedEx R , DHL R and UPS R , oer a number of dierent shipping options, each with specic costs associated. Create an inheritance hierarchy to represent various types of packages. Use Package as the base class of the hierarchy, then include classes TwoDayPackage and OvernightPackage that derive from Package. Base class Package should include data members representing the name, address, city, state and ZIP code for both the sender and the recipient of the package, in addition to data members that store the 63

weight (in ounces) and cost per ounce to ship the package. Packages constructor should initialize these data members. Ensure that the weight and cost per ounce contain positive values. Package should provide a public member function calculateCost that returns a double indicating the cost associated with shipping the package. Packages calculateCost function should determine the cost by multiplying the weight by the cost per ounce. Derived class TwoDayPackage should inherit the functionality of base class Package, but also include a data member that represents a at fee that the shipping company charges for two-day-delivery service. TwoDayPackages constructor should receive a value to initialize this data member. TwoDayPackage should redene member function calculateCost so that it computes the shipping cost by adding the at fee to the weight-based cost calculated by base class Packages calculateCost function. Class OvernightPackage should inherit directly from class Package and contain an additional data member representing an additional fee per ounce charged for overnight-delivery service. OvernightPackage should redene member function calculateCost so that it adds the additional fee per ounce to the standard cost per ounce before calculating the shipping cost. Write a test program that creates objects of each type of Package and tests member function calculateCost. Note: Both TwoDayPackage and OvernightPackage only dier in at fee value. C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < s t r i n g > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Package { public : Package ( c o n s t s t r i n g& name , c o n s t s t r i n g& a d d r e s s , c o n s t s t r i n g& c i t y , c o n s t Real& s e n d e r Z I P , c o n s t Real& r e c e i v e r Z I P , c o n s t Real& weight , c o n s t Real& c o s t ) : name ( name ) , a d d r e s s ( a d d r e s s ) , c i t y ( c i t y ) , s e n d e r Z I P ( s e n d e r Z I P ) , r e c e i v e r Z I P ( r e c e i v e r Z I P ) , weight ( weight ) , c o s t ( c o s t ) { validate () ; } v i r t u a l Package ( ) {} Real C a l c u l a t e C o s t ( ) { r e t u r n w e i g h t Real g e t w e i g t h ( ) { r e t u r n w e i g h t ; } cost ;}

11

13

15

17

19

64

private : void v a l i d a t e ( ) { QL REQUIRE( ( w e i g h t positive values ) ; }

>= 0 && c o s t

>= 0 ) , E r r o r : w i e g t h and c o s t must be

s t r i n g name , a d d r e s s , c i t y ; Real s e n d e r Z I P , r e c e i v e r Z I P , w e i g h t , c o s t ; }; c l a s s TwoDayPackage : p u b l i c Package { public : TwoDayPackage ( c o n s t s t r i n g& name , c o n s t s t r i n g& a d d r e s s , c o n s t s t r i n g& c i t y , c o n s t Real& s e n d e r Z I P , c o n s t Real& r e c e i v e r Z I P , c o n s t Real& weight , c o n s t Real & c o s t , c o n s t Real& F l a t F e e ) : Package ( name , a d d r e s s , c i t y , s e n d e r Z I P , r e c e i v e r Z I P , weight , c o s t ) , F l a t F e e ( F l a t F e e ) {} v i r t u a l TwoDayPackage ( ) {} Real C a l c u l a t e C o s t ( ) { r e t u r n Package : : C a l c u l a t e C o s t ( ) + ( Package : : g e t w e i g t h ( ) F l a t F e e ) ; } private : Real F l a t F e e ; }; c l a s s OvernightPackage : p u b l i c Package { public : OvernightPackage ( c o n s t s t r i n g& name , c o n s t s t r i n g& a d d r e s s , c o n s t s t r i n g& c i t y , c o n s t Real& s e n d e r Z I P , c o n s t Real& r e c e i v e r Z I P , c o n s t Real& weight , c o n s t Real& c o s t , c o n s t Real& F l a t F e e ) : Package ( name , a d d r e s s , c i t y , s e n d e r Z I P , r e c e i v e r Z I P , weight , c o s t ) , F l a t F e e ( F l a t F e e ) {} Real C a l c u l a t e C o s t ( ) { r e t u r n Package : : C a l c u l a t e C o s t ( ) + ( Package : : g e t w e i g t h ( ) F l a t F e e ) ; } private : Real F l a t F e e ; };

11

13

15

17

19

21

23

25

27

29

31

33

65

10

i n t main ( ) { try { // P e r s o n a l i n f o r m a t i o n s t r i n g name ( M a u r i c i o ) ; s t r i n g a d d r e s s ( C a l l e Aragon 25 ) ; s t r i n g c i t y ( Madrid / Spain ) ; Real s e n d e r Z I P ( 2 8 9 1 1 ) ; Real r e c e i v e r Z I P ( 2 8 9 1 2 ) ; // Package c h a r a c t e r i s t i c s Real Weight ( 1 2 0 ) ; Real c o s t p e r o u n c e ( 3 . 4 6 7 5 ) ; // Overnigth f e e Real o v e r n i g h t F e e ( 4 . 5 ) ; // Twoday f e e Real TwodayFee ( 2 . 3 5 ) ;

12

14

16

18

20

22

OvernightPackage ON( name , a d d r e s s , c i t y , s e n d e r Z I P , r e c e i v e r Z I P , Weight , cost per ounce , overnightFee ) ;


24

TwoDayPackage TwoDays ( name , a d d r e s s , c i t y , s e n d e r Z I P , r e c e i v e r Z I P , Weight , c o s t p e r o u n c e , TwodayFee ) ;


26

28

c o u t << Overnight t o t a l c o s t : << ON. C a l c u l a t e C o s t ( ) << e n d l ; c o u t << Two days t o t a l c o s t : << TwoDays . C a l c u l a t e C o s t ( ) << e n d l ; }

30

32

34

c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

42.

Exercise 41 (12.10 in book)

(Account Inheritance Hierarchy) Create an inheritance hierarchy that a bank might use to represent customers bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specic types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, on the other hand, charge a fee per transaction (i.e., credit or debit).

66

Create an inheritance hierarchy containing base class Account and derived classes SavingsAccount and CheckingAccount that inherit from class Account. Base class Account should include one data member of type double to represent the account balance. The class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0.0. If not, the balance should be set to 0.0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and ensure that the debit amount does not exceed the Accounts balance. If it does, the balance should be left unchanged and the function should print the message Debit amount exceeded account balance.Member function getBalance should return the current balance. Derived class SavingsAccount should inherit the functionality of an Account, but also include a data member of type double indicating the interest rate (percentage) assigned to the Account. SavingsAccounts constructor should receive the initial balance, as well as an initial value for the SavingsAccounts interest rate. SavingsAccount should provide a public member function calculateInterest that returns a double indicating the amount of interest earned by an account. Member function calculateInterest should determine this amount by multiplying the interest rate by the account balance. [Note: SavingsAccount should inherit member functions credit and debit as is without redening them.] Derived class CheckingAccount should inherit from base class Account and include an additional data member of type double that represents the fee charged per transaction. CheckingAccounts constructor should receive the initial balance, as well as a parameter indicating a fee amount. Class CheckingAccount should redene member functions credit and debit so that they subtract the fee from the account balance whenever either transaction is performed successfully. CheckingAccounts versions of these functions should invoke the base-class Account version to perform the updates to an account balance. CheckingAccounts debit function should charge a fee only if money is actually withdrawn (i.e., the debit amount does not exceed the account balance). [Hint: Dene Accounts debit function so that it returns a bool indicating whether money was withdrawn. Then use the return value to determine whether a fee should be charged.] After dening the classes in this hierarchy, write a program that creates objects of each class and tests their member functions. Add interest to the SavingsAccount object by rst invoking its calculateInterest function, then passing the returned interest amount to the objects credit function.

67

C++ code
1

#i n c l u d e < i o s t r e a m > #i n c l u d e < s t r i n g > #i n c l u d e < q l / q u a n t l i b . hpp> u s i n g namespace s t d ; u s i n g namespace QuantLib ; c l a s s Account { public : Account ( c o n s t Real& AccountBalance ) : AccountBalance ( AccountBalance ) { v a l i d a t e ( ) ;} v i r t u a l Account ( ) {} v o i d c r e d i t ( c o n s t Real& amount ) { QL REQUIRE( ( amount > 0) , E r r o r : amount must be p o s i t i v e . ) ; AccountBalance += amount ; } v o i d d e b i t ( c o n s t Real& amount ) { QL REQUIRE( ( amount <= AccountBalance ) , E r r o r : Debit amount e x c e e d e d account balance . ) ; AccountBalance = amount ; } Real g e t B a l a n c e ( ) { r e t u r n AccountBalance ; } v o i d s e t B a l a n c e ( c o n s t Real& new AccountBalance ) { AccountBalance = new AccountBalance ; } private : Real AccountBalance ; void v a l i d a t e ( ) { i f ( AccountBalance < 0 . 0 ) { c o u t << E r r o r : Balance must be p o s i t i v e . \ n ; AccountBalance = 0 . 0 ; } } };

11

13

15

17

19

21

23

25

27

29

31

33

35

37

39

41

68

c l a s s SavingAccount : p u b l i c Account { public : SavingAccount ( c o n s t Real& AccountBalance , c o n s t Real& I n t e r e s t R a t e ) : Account ( AccountBalance ) , I n t e r e s t R a t e ( I n t e r e s t R a t e ) {} Real C a l c u l a t e I n t e r e s t ( ) { / To c a l c u l a t e i n t e r e s t , t h i s f u n c t i o n must be c a l l e d . In t h e e x e r c i s e , d o e s n t d e f i n e any c r i t e r i a t o update b a l a n c e / Real I n t e r e s t = Account : : g e t B a l a n c e ( ) I n t e r e s t R a t e ; Real new Balance = Account : : g e t B a l a n c e ( ) ( 1 + I n t e r e s t R a t e ) ; Account : : s e t B a l a n c e ( new Balance ) ; // Update Balance . return Interest ; } private : Real I n t e r e s t R a t e ; void v a l i d a t e ( ) {QL REQUIRE( ( I n t e r e s t R a t e interest rate . ) ;} };

10

12

14

16

18

20

>= 0 && I n t e r e s t R a t e

< 1 ) , E r r o r : non p e r c e n t a g e

22

24

26

28

c l a s s CheckingAccount : p u b l i c Account { public : CheckingAccount ( c o n s t Real& AccountBalance , c o n s t Real& f e e ) : Account ( AccountBalance ) , f e e ( f e e ) { validate () ;} v o i d c r e d i t ( c o n s t Real& amount ) { QL REQUIRE( ( amount >= 0 ) , E r r o r : N e g a t i v e amount . ) ; b o o l A = ! c l o s e ( amount , 0 ) ; // A = 1 i f t r a n s a c t i o n i f (A == 1 ) { Real new Balance = Account : : g e t B a l a n c e ( ) + amount ( 1 f e e ) ; ; Account : : s e t B a l a n c e ( new Balance ) ; } } v o i d d e b i t ( c o n s t Real& amount ) { QL REQUIRE( ( amount >= 0 ) , E r r o r : N e g a t i v e amount . ) ; Real new Balance = Account : : g e t B a l a n c e ( ) amount ( 1 + f e e ) ;

30

32

34

36

38

40

42

44

46

69

QL REQUIRE( ( new Balance >= 0 ) , E r r o r : Debit amount + f e e s , e x c e e d e d a c c o u n t balance . ) ;


2

b o o l A = ! c l o s e ( amount , 0 ) ; // A = 1 i f t r a n s a c t i o n i f (A == 1 ) { Account : : s e t B a l a n c e ( new Balance ) ; } } private : Real f e e ; void v a l i d a t e ( ) {QL REQUIRE( ( f e e };

10

12

>= 0 && f e e

< 1 ) , E r r o r : non p e r c e n t a g e i n t e r e s t r a t e . ) ; }

14

16

18

20

i n t main ( ) { try { // Test SavingAccount SavingAccount A( 1 0 0 0 , 0 . 1 ) ; c o u t << SAVING ACCOUNT TEST \ n \ n ; c o u t << I n i t i a l Balance : << A. g e t B a l a n c e ( ) << e n d l ; c o u t << Saving a c c o u n t i n t e r e s t e a r n e d : << A. C a l c u l a t e I n t e r e s t ( ) << e n d l ; c o u t << New s a v i n g a c c o u n t b a l a n c e i s : << A. g e t B a l a n c e ( ) << e n d l ; c o u t << Debit 200 form b a l a n c e \ n ; A. d e b i t ( 2 0 0 ) ; c o u t << New s a v i n g a c c o u n t b a l a n c e i s : << A. g e t B a l a n c e ( ) << e n d l ; c o u t << C r e d i t 150 form b a l a n c e \ n ; A. c r e d i t ( 1 5 0 ) ; c o u t << New s a v i n g a c c o u n t b a l a n c e i s : << A. g e t B a l a n c e ( ) << e n d l ; c o u t << \ n \ n ; // Test CreditAccount CheckingAccount B( 1 0 0 0 , 0 . 0 5 ) ; c o u t << CHECKING ACCOUNT TEST \ n \ n ; c o u t << I n i t i a l Balance : << B . g e t B a l a n c e ( ) << e n d l ; c o u t << Debit 0 form b a l a n c e \ n ; B. debit (0) ; // No t r a n s a c t i o n f e e , same b a l a n c e c o u t << Balance : << B . g e t B a l a n c e ( ) << e n d l ;

22

24

26

28

30

32

34

36

38

40

42

44

70

c o u t << Debit 100 form b a l a n c e \ n ; // Fees e q u a l t o 5 = 100 0 . 0 5 B. debit (100) ; c o u t << Balance : << B . g e t B a l a n c e ( ) << e n d l ; c o u t << C r e d i t 0 form b a l a n c e \ n ; B. c r e d i t (0) ; // No t r a n s a c t i o n f e e , same b a l a n c e c o u t << Balance : << B . g e t B a l a n c e ( ) << e n d l ;

10

12

c o u t << C r e d i t 100 t o b a l a n c e \ n ; // Fees e q u a l t o 5 = 100 0 . 0 5 B. c r e d i t (100) ; c o u t << Balance : << B . g e t B a l a n c e ( ) << e n d l ; } c a t c h ( s t d : : e x c e p t i o n& e ) { c e r r << e . what ( ) << e n d l ; } }

14

16

18

20

71

Anda mungkin juga menyukai