+ All Categories
Home > Documents > C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming...

C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming...

Date post: 06-Jul-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
39
A C/C++ Programming Tutorial A.1 Introduction This tutorial introduces a minimal subset of C/C++ that should be sufficient to complete the optional progamming exercises in this book. The programs here run from the command line—the Command Prompt applica- tion in Windows, or the Terminal application in MacOS X or other flavors of UNIX. The discussion here assumes some basic knowledge of how to use the command line. You should know at a minimum how to start and exit the command line application, and how to list files and folders (dir on Windows, and ls on MacOS X or other UNIX systems). You should also know how to parse file pathnames on your system (for example, “C:\Files\test.cpp” on Windows which means that the file test.cpp is in the top- level folder “My Files” which is on the drive labelled “C”. On MacOS X we could have “/home/myname/test.cpp” which means that test.cpp is in the folder “myname” which is in the enclosing top-level folder “home”.) C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not use this extra layer except for the routines for reading and writing to the computer screen (input-output or I/O). C/C++ is a compiled language. This means that programming proceeds in two steps. First, we write the source program in C/C++. This is in a plain text file with the filename ending in the extension .cpp (e.g., test.cpp). Second, we compile the source program by running a compiler such as g++. If using g++, we could type in a command such as the following at the command prompt: g++ test.cpp -o test.exe © Springer Nature Singapore Pte Ltd. 2020 S. Lynn, Valuation for Accountants, Springer Texts in Business and Economics, https://doi.org/10.1007/978-981-15-0357-3 299
Transcript
Page 1: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

AC/C++ Programming Tutorial

A.1 Introduction

This tutorial introduces a minimal subset of C/C++ that should be sufficient tocomplete the optional progamming exercises in this book.

The programs here run from the command line—the Command Prompt applica-tion in Windows, or the Terminal application in MacOS X or other flavors of UNIX.The discussion here assumes some basic knowledge of how to use the commandline. You should know at a minimum how to start and exit the command lineapplication, and how to list files and folders (dir on Windows, and ls on MacOSX or other UNIX systems).

You should also know how to parse file pathnames on your system (for example,“C:\Files\test.cpp” on Windows which means that the file test.cpp is in the top-level folder “My Files” which is on the drive labelled “C”. On MacOS X we couldhave “/home/myname/test.cpp” which means that test.cpp is in the folder “myname”which is in the enclosing top-level folder “home”.)

C/C++ is a commonly used computer programming language. C++ is an extralayer on top of an older language called C. We will not use this extra layer exceptfor the routines for reading and writing to the computer screen (input-output or I/O).

C/C++ is a compiled language. This means that programming proceeds in twosteps.

First, we write the source program in C/C++. This is in a plain text file with thefilename ending in the extension .cpp (e.g., test.cpp).

Second, we compile the source program by running a compiler such as g++. Ifusing g++, we could type in a command such as the following at the commandprompt:

g++ test.cpp -o test.exe

© Springer Nature Singapore Pte Ltd. 2020S. Lynn, Valuation for Accountants, Springer Texts in Business and Economics,https://doi.org/10.1007/978-981-15-0357-3

299

Page 2: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

300 A C/C++ Programming Tutorial

This command would read the source program test.cpp and create an executablefile (a set of machine-readable instructions) called test.exe. We can directly run thefile test.exe by entering its name at the command prompt:

test.exe

On some UNIX platforms such as MacOS X, we may need to first set the userpermissions to make the file runnable, by issuing the following command at thecommand prompt:

chmod u+x test.exe

We may also need to specify the path when running the executable, as follows:

./test.exe

where . is UNIX shorthand for the current directory (folder). This is because UNIXsystems are often configured not to look for executables in the current directoryunless this directory is specifically indicated when calling the executable.

A.2 Getting the C/C++ Compiler

While any C/C++ compiler should work fine with our programs, it is recommendedthat you get the GNU C/C++ compiler gcc (or its near-equivalent Clang). Thesework similarly on all major platforms. We will assume the GNU C/C++ compiler inthe examples that follow.

To get the GNU C/C++ compiler for Windows, you can install mingw (minimal-ist GNU for Windows), currently available at http://www.mingw.org. An alternativeis Cygwin, which is currently available at http://www.cygwin.com.

To install the gcc compiler on Mac OS X (actually Clang), you would installthe command line tools for XCode, from the Apple developer website at http://developer.apple.com.

On other UNIX-based systems such as Linux, the GNU compiler or equivalent istypically a standard part of the platform and is likely to be pre-installed. If not pre-installed, it should be easy to install using the standard package installation process.Check your system documentation.

You can also install gcc (actually Clang) on a smartphone running Androidby installing the “termux” app, which produces a UNIX command prompt. Onceinstalled, you can use the following command to install gcc:

pkg install clang

It is also desirable on Termux to install a user-friendly text editor such as nanoon Termux to edit programs (pkg install nano).

Page 3: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.3 Program Format 301

A.3 Program Format

All the programs in our exercises follow a consistent format. They ask the user toinput various parameters for some model, say a binomial lattice model for optionvaluation. Then they run the model with these parameters. Finally they print out themodel output, say the option value.

All the action takes place at the command prompt. So to run these programs, opena command prompt window in Windows, or run the Terminal app in MacOS X (orLinux etc.).

To illustrate the basic format of a program, we will start with a simple programthat does nothing. Let us call this program donothing.cpp.

A.3.1 The #include Directive

The opening lines of the program are calls to include various standard C source filesin our program so that we can use the standard routines defined in these files. Wewill consistently include two standard files: iostream, which defines the standardC++ I/O routines, and “math.h” which defines several math functions (in plain C)that we will use in our programs.

To include a standard C/C++ source file, we use the invocation:

#include <... >

TaskTry to write out the commands to include iostream and math.h, before looking atthe solution given below:

Solution

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

A.3.2 The Program Body

C programs are built up out of functions. A function has a standard format asfollows:

Type_Of_Return_Value n a m e _ o f _ f u n c t i o n ( l i s t _ o f _ i n p u t s ) {

C / C++ s t a t e m e n t _ e n d i n g _ i n _ s e m i c o l o n ;C / C++ s t a t e m e n t _ e n d i n g _ i n _ s e m i c o l o n ;. . .

}

Every runnable program must have a function called main. By convention,this function returns a value of type “int” or integer (a positive or negative wholenumber).

Page 4: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

302 A C/C++ Programming Tutorial

TaskCreate and compile a program donothing.cpp with our standard headers followed byan empty main function (the input list is blank and there are no C/C++ statementsin the body). This must be a plain text file. So do not use a word-processor like MSWord to create the file. Use a text editor like Notepad on Windows or TextEdit onthe Mac. After saving, compile and check that your program works by running theexecutable donothing.exe.

Be careful that C/C++ is case-sensitive. This means that “main” is not the sameas “Main” or “mAin” or “MAIN”.

Solution (donothing.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {}

Compiler Commandg++ donothing.cpp -o donothing.exe

A.3.3 Comments

Comments are memos to the human reader (you, the programmer) that are ignoredby the compiler.

Comments in C are enclosed within the symbols /∗ . . . ∗/.In addition, C++ allows comments that start with the symbol // and run to the

end of the current line.

TaskEdit donothing.cpp to include C- and C++-style comments that say “This programdoes nothing”. You can put them anywhere in the program.

Solution (donothing.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

/ / Th i s program does n o t h i n g

i n t main ( ) {/∗ Thi s program

doesn o t h i n g ∗ /

}

Page 5: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.4 Printing Text to the Screen 303

A.4 Printing Text to the Screen

Strings of text are enclosed in double inverted commas (double quotes) as in “hello”.These are called strings in computer programming jargon.

The C++ command to print a string to the screen is:

std::cout «...

The prefix std signifies that cout is a command that is defined in the standardnamespace (“std”). This is to avoid any conflict in case cout is defined somewhereelse in your program.

The items to be printed to the screen are separated by the symbol “«”. You canremember this by thinking of an open mouth spitting out something (output).

The items to be printed to the screen could include strings, variables (to bediscussed soon), mathematical expressions (to be discussed later), and a specialcommand to signify end of line: std::endl.

For example, if we have a variable named x and we want to print out “The valueof x is: ” followed by the value of x, followed by a new line, we would include theC++ statement:

s t d : : c o u t << ‘ ‘ The v a l u e o f x i s : ’ ’<< x << s t d : : e n d l ;

Do not forget the semicolon. In the body of a function, every C/C++ statementmust end with a semicolon.

Task

Create and run a program called helloworld.cpp (executable helloworld.exe)that prints the text “Hello World!” followed by a new line.

Solution (helloworld.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {s t d : : c o u t << " H e l l o wor ld ! " << s t d : : e n d l ;

}

Page 6: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

304 A C/C++ Programming Tutorial

A.5 Variables

A variable is an item that can take on different values in the course of a program.In C/C++, although a variable can take on different values, the values must all

be of the same type, for example whole number or decimal. We need to declare thetype of a variable before we use that variable.

We will just consider two types in our minimal subset of C/C++ (there are manyothers):

int an integer, a whole number which could be positive or negative, e.g., -1, 2, 3, 0, 500are all integers.

double a decimal, e.g., 7.89, 0.1453, -1.0, or -1.859.

To declare the type of a variable, we type int or double followed by the name ofthe variable and ending of course in a semicolon.

For example, to declare an integer called x, we type

i n t x ;

To declare a double named y, we type

d o u b l e y ;

We can declare multiple variables of the same type by separating the variablenames with commas.

Thus to declare two integers z and a in the same statement, we type:

i n t z , a ;

A.5.1 Assigning Values to Variables

To set a variable equal to a number (or another variable), we use the equals sign “=”.For example, to set the variable x to be equal to 1, we type:

x = 1 ;

This assigns the value 1 to the variable x. We can think of this as shorthand forthe natural-language command:

SET x TO BE EQUAL TO 1 .

The order is important. The command 1 = x is wrong. The variable to beassigned to (x) is always on the left hand side, and the value to be assigned (1)is always on the right hand side.

To set the variable y to be equal to the variable z (that is, the value currentlystored in the variable z), we type:

y = z ;

Page 7: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.7 Mathematics 305

A.6 Keyboard Input

To input a number from the keyboard, we use the std::cin command.The format is:

s t d : : c i n >> v a r i a b l e _ n a m e ;

where variable_name is the variable in which the inputed value would bestored.

For example, to read in some number into a variable named x, we would type:

s t d : : c i n >> x ;

You can remember the symbol » as a mouth that is closing to ingest something(input).

Task

Write a program called readnumber.cpp that:

1. Asks the user to input a number. (Hint: use cout.)2. Reads the number into a variable called x. (Hint: Don’t forget the variable

declaration).3. Print out “The number you typed is:” followed by the number.

Solution (readnumber.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {i n t x ;s t d : : c o u t << " I n p u t a number : " ;s t d : : c i n >> x ;s t d : : c o u t << " The number you e n t e r e d i s : " << x <<

s t d : : e n d l ;}

A.7 Mathematics

Common mathematical operations are as follows:

Page 8: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

306 A C/C++ Programming Tutorial

+ addition, e.g., a + b.

− subtraction, e.g., a − b.

∗ multiplication, e.g., a ∗ b means a × b.

/ division, e.g., a/b.

% x%y (x modulo y) gives the remainder when x is divided by y.

pow(a, b) a to the power of b (ab).

exp(a) e to the power of a (ea).

log(a) Natural logarithm of a (ln(a)).

sqrt(a) Square root of a (√

a).

sin(a) Sine of a.

cos(a) Cosine of a.

tan(a) Tangent of a.

asin(a) Arcsine of a.

atan(a) Arctangent of a.

M_PI The standard constant π .

We can also group expressions using parentheses (...) as in standard algebra. Ina complex expression, operations are evaluated in the same order as in standardalgebra, that is, first items grouped in parentheses, then exponents (powers androots), then multiplication and division, then addition and subtraction. We canremember this using the mnemonic PEMDAS.

Examples

a = b + c replaces a with the sum of b and c.

a = a + 1 replaces a with its original value plus 1.

a = pow(a,2) replaces a with its original value squared.

Task

Write a program findpv.cpp that finds the present value of some amount A after nyears at an APR rate r based on compounding k times per year (n and k can berestricted to be integers).

Your program should first request values for A,n,r and k, and then calculate thepresent value, and finally print out the present value.

Solution (findpv.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

Page 9: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.7 Mathematics 307

i n t main ( ) {d o u b l e A, r , pv ;i n t n , k ;

s t d : : c o u t << " I n p u t f u t u r e amount : " ;s t d : : c i n >> A;s t d : : c o u t << " I n p u t t ime t o m a t u r i t y i n y e a r s : " ;s t d : : c i n >> n ;s t d : : c o u t << " I n p u t APR d i s c o u n t r a t e ( a s a d e c i m a l ) : " ;s t d : : c i n >> r ;s t d : : c o u t << " Number o f compounding p e r i o d s p e r y e a r : " ;s t d : : c i n >> k ;

pv = A / pow (1 + r / k , n∗k ) ;s t d : : c o u t << " P r e s e n t v a l u e i s " << pv << s t d : : e n d l ;

}

We could also directly include the present value expression in the final std::coutstatement, in which case we would not need the variable pv. This would look like:

s t d : : c o u t << " P r e s e n t v a l u e i s "<< A / pow (1 + r / k , n∗k )<< s t d : : e n d l ;

Task

Write a program findpvcontinuous.cpp that finds the present value of A after nyears compounded at a continuously compounded rate rc. (Hint: copy the previousprogram to a new file named findpvcontinuous.cpp and then make a few changes).

Solution (findpvcontinuous.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {d o u b l e A, rc , pv ;i n t n ;

s t d : : c o u t << " I n p u t f u t u r e amount : " ;s t d : : c i n >> A;s t d : : c o u t << " I n p u t t ime t o m a t u r i t y i n y e a r s : " ;s t d : : c i n >> n ;s t d : : c o u t << " I n p u t c o n t i n u o u s l y compounded d i s c o u n t

r a t e "<< " ( as a d e c i m a l ) : " ;

Page 10: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

308 A C/C++ Programming Tutorial

s t d : : c i n >> r c ;

pv = A/ exp ( r c ∗n ) ;s t d : : c o u t << pv << s t d : : e n d l ;

}

Task

Write a program ratorc.cpp that finds the continuously compounded rate rc thatcorresponds to a given annually compounded rate ra. Ask the user for the annuallycompounded rate, then do the conversion and report the equivalent continuouslycompounded rate.

Solution (ratorc.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {d o u b l e ra , r c ;

s t d : : c o u t << " I n p u t a n n u a l l y compounded r a t e : " ;s t d : : c i n >> r a ;r c = l o g (1 + r a ) ;s t d : : c o u t << " The e q u i v a l e n t c o n t i n u o u s l y

compounded r a t e i s : "<< r c << s t d : : e n d l ;

}

A.8 Conditionals

We may want a program to branch in different directions depending on sourcecondition. We can use an if statement to achieve this. This is of the form:

i f ( . . . ) {. . .}e l s e i f ( . . . ) {. . .}. . .e l s e {. . .}

Page 11: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.8 Conditionals 309

The above is a skeleton of a program that first checks if some condition is true:the condition in the parentheses following if. If the condition is true, the programfollows the instructions within the braces ... that follows the initial if (...) statement.

If the statement is not true, we can have zero or more else if statements thattest for some other conditions, and execute the instructions that follow if thoseconditions are true.

We can also finally have zero or one else ... blocks that perform the defaultaction if none of the above conditions are true.

Conditions can be stated in the following forms:

a == b tests if a equals b.

Not the same as a = b.

a <= b tests if a is less than or equal to b.

a < b tests if a is less than b.

a >= b tests if a is greater than or equal to b.

a > b tests if a is greater than b.

a! = b tests if a is not equal to b.

We can also join together logical conditions using “&&” (and), or “||” (or).For example, we can read the following:

i f ( a >= 1 && a <= 5)}

as: “If (a is greater than or equal to 1) AND (a is less than or equal to 5)” (inother words, a lies between 1 and 5).

Example

i f ( x == 1){s t d : : c o u t << 1 << s t d : : e n d l ;

}e l s e i f ( x == 2) {

s t d : : c o u t << 2 << s t d : : e n d l ;}e l s e {

s t d : : c o u t << "Some o t h e r number " << s t d : : e n d l ;}

We can nest if ... else loops inside each other, as in:

i f ( . . . ) {i f ( . . . ) {

. . .}

}

Page 12: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

310 A C/C++ Programming Tutorial

Task

Write a program optionvalue.cpp that finds the value of an option on a shareat the exercise date given the strike price K, the share price at the expiry date St, anda variable isput that equals 1 if the option is a put and 0 if it is a call.

Your program should first ask the user to input the parameters, then calculate andoutput the option value at exercise. Recall that for a call, the option value is givenby the higher of St − K and 0. For a put, the option value is given by the higher ofK − St and zero.

Solution (optionvalue.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {d o u b l e K, St , o p t i o n v a l u e ;i n t i s p u t ;

s t d : : c o u t << " I n p u t s t r i k e p r i c e : " ;s t d : : c i n >> K;s t d : : c o u t << " I n p u t s h a r e p r i c e a t o p t i o n e x p i r y : " ;s t d : : c i n >> St ;s t d : : c o u t << " I n p u t 1 f o r put , 0 ( o r a n y t h i n g e l s e )

f o r c a l l : " ;s t d : : c i n >> i s p u t ;

i f ( i s p u t == 1){ / / p u ti f (K > St ) {

o p t i o n v a l u e = K − St ;}e l s e {

o p t i o n v a l u e = 0 ;}

}e l s e { / / c a l l

i f ( S t > K) {o p t i o n v a l u e = S t − K;

}e l s e {

o p t i o n v a l u e = 0 ;}

}

Page 13: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.9 Loops 311

s t d : : c o u t << " The o p t i o n v a l u e a t e x p i r y i s : "<< o p t i o n v a l u e << s t d : : e n d l ;

}

A.9 Loops

One of the most useful devices in a program is a loop—a routine that runs a sequenceof instructions multiple times. There are a number of looping commands in C/C++,but for our purposes, it is sufficient to consider one—the for loop. This is of theform:

f o r ( i n i t i a l _ c o n d i t i o n ; l o o p _ c o n d i t i o n ; c h a n g e _ e a c h _ s t e p ) {commands_ to_be_repea ted

}

Here initial_condition is the starting point of the loop, usually setting a counteror index equal to some starting value such as zero or 1.

The loop will keep repeating while the second condition, the loop_condition istrue. Usually this is a condition that the counter is less than or less than or equal tosome maximum stopping value. When the counter reaches that value, the loop stopsrunning.

The change_each_step is some action that takes place each time the loop is run.For example, the counter could increase by 1.

Here is a simple example loop that runs 10 times and prints out the numbers from1 to 10:

f o r ( c t r = 1 ; c t r <= 1 0 ; c t r = c t r +1){s t d : : c o u t << c t r << s t d : : e n d l ;

}

One convenient shorthand that C/C++ allows is to replace the statement x=x+1with the statement x++. Similarly, we can replace x=x-1 with x-.

So we can rewrite the loop above as:

f o r ( c t r = 1 ; c t r <= 1 0 ; c t r ++){s t d : : c o u t << c t r << s t d : : e n d l ;

}

Task

Write a program pvannuity.cpp that finds the present value of an annuity for10 years that is CU 10 in the first year, and increases by a fixed amount of CU 0.80each subsequent year (i.e., CU 10 in Year 1, CU 10.80 in Year 2, . . . ) The forwarddiscount rate is 6% in year 1, and increases by 10 basis points each subsequent year(i.e., we discount by 6% from year 1 to year 0, by 6.1% from year 2 to year 1, by6.2% from year 3 to year 2 . . . ).

Page 14: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

312 A C/C++ Programming Tutorial

Solution (pvannuity.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {

d o u b l e amount , d i s c o u n t r a t e , d i s c o u n t f a c t o r , p v a n n u i t y ;i n t c t r ;

amount = 1 0 . 0 ;d i s c o u n t r a t e = 0 . 0 6 ;d i s c o u n t f a c t o r = 1 / ( 1 + d i s c o u n t r a t e ) ;p v a n n u i t y = amount∗ d i s c o u n t f a c t o r ;

f o r ( c t r =2 ; c t r <=10; c t r ++){amount = amount + 0 . 8 0 ;d i s c o u n t r a t e = d i s c o u n t r a t e + 0 . 0 0 1 ;d i s c o u n t f a c t o r = d i s c o u n t f a c t o r ∗1 / ( 1 + d i s c o u n t r a t e ) ;p v a n n u i t y = p v a n n u i t y + amount∗ d i s c o u n t f a c t o r ;

}

s t d : : c o u t << " P r e s e n t v a l u e o f t h e a n n u i t y i s : "<< p v a n n u i t y << s t d : : e n d l ;

}

Loops can be nested inside other loops. The following task implements this.

Task

A binomial lattice for option valuation starts from an initial share price S0, then atthe first step branches to an up step Su = S0 × u or a down step Sd = S0 × d.We continue the process by adding up and down branches to each subsequent price,where the up step involves multiplication by the up factor u and the down stepinvolves multiplication by the down factor d, until we reach the option expiry date.

Write a program binomialprices.cpp that asks for the initial price S0, thenumber of steps to expiry n, the up factor u, and the down factor d.

Given this information, print out the prices at each step as follows:

Step 0: S0

Step 1: S0 × u S0 × d

Step 2: S0 × u × u S0 × u × d S0 × d × d

...

Page 15: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.9 Loops 313

Solution (binomialprices.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {d o u b l e S0 , s t a r t p r i c e , u , d ;i n t n , c t r 1 , c t r 2 ;

s t d : : c o u t << " I n p u t i n i t i a l s h a r e p r i c e : " ;s t d : : c i n >> S0 ;s t d : : c o u t << " I n p u t up s t e p f a c t o r : " ;s t d : : c i n >> u ;s t d : : c o u t << " I n p u t down s t e p f a c t o r : " ;s t d : : c i n >> d ;s t d : : c o u t << " I n p u t number o f s t e p s : " ;s t d : : c i n >> n ;

s t d : : c o u t << S0 << s t d : : e n d l ;

s t a r t p r i c e = S0∗u ;/ / f i r s t p r i c e i n t h e n e x t l i n e

f o r ( c t r 1 = 1 ; c t r 1 <= n ; c t r 1 ++){

/ / p r i n t f i r s t p r i c e i n t h e l i n eS0 = s t a r t p r i c e ;s t d : : c o u t << S0 << " " ;

/ / each s u b s e q u e n t p r i c e i s t h e p r e v i o u s p r i c e t i m e s d / uf o r ( c t r 2 = 1 ; c t r 2 <= c t r 1 ; c t r 2 ++){

S0=S0∗d / u ;s t d : : c o u t << S0 << " " ;

}s t d : : c o u t << s t d : : e n d l ;

/ / u p d a t e s t a r t p r i c e f o r t h e n e x t l i n es t a r t p r i c e = s t a r t p r i c e ∗u ;

}}

Two useful commands help us to break out of a loop early. These are:

b r e a k ;

Page 16: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

314 A C/C++ Programming Tutorial

which exits the loop completely when encountered; and:

n e x t ;

which jumps immediately to the next round of the loop, ignoring any remainingcommands in the current round.

These commands would typically be used inside an if ... block.

A.10 Arrays

An array is a list of items of a particular type (like int or double). We can refer tothe n’th item in an array called say arry as arry[n]. Array indices start from 0.

To declare an array, we use the format:

t y p e a r r ayname [ max imum_index_o f_ i t ems_ in_a r r ay ] ;

For example, to declare an array called arry with 5 items that are integers, wehave:

i n t a r r y [ 4 ] ;

To assign a value to an item in an array, we simply use:

a r rayname [ i n d e x ] = v a l u e ;

For example, to assign the value 3 to arry[2], we have:

a r r y [ 2 ] = 3 ;

Arrays can also be two-dimensional (or more). We can think of a two-dimensional array as a table or matrix in which the first index refers to the rownumber and the second to the column number.

For a two-dimensional array called arry2d with 3 × 3 items of type double, theformat to declare the array would be:

d o u b l e a r r y 2 d [ 2 ] [ 2 ] ;

To assign the value 3.5 to the 1st row (index 0) and the 2nd column (index 1), wewould have:

a r r y 2 d [ 0 ] [ 1 ] = 3 . 5 ;

Task

Write a program arry.cpp that creates an array with 5 items. Fill the array with thenumbers from 5 to 10 in order using a loop. Print out the array with items separatedby spaces.

Page 17: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.10 Arrays 315

Solution (arry.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {i n t a r r y [ 4 ] , c t r ;

f o r ( c t r =5 ; c t r <=10; c t r ++){a r r y [ c t r −5]= c t r ;s t d : : c o u t << a r r y [ c t r −5] << " " ;

}s t d : : c o u t << s t d : : e n d l ;

}

Task

Rewrite binomialprices.cpp using a two-dimensional array of prices (copythe original to a new file binomialprices2.cpp and then make changes). Youcan declare the array using some large number of rows and columns say 100 × 100.

Solution (binomialprices2.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

i n t main ( ) {d o u b l e S0 [ 1 0 0 ] [ 1 0 0 ] , u , d ;i n t n , c t r 1 , c t r 2 ;

s t d : : c o u t << " I n p u t i n i t i a l s h a r e p r i c e : " ;s t d : : c i n >> S0 [ 0 ] [ 0 ] ;s t d : : c o u t << " I n p u t up s t e p f a c t o r : " ;s t d : : c i n >> u ;s t d : : c o u t << " I n p u t down s t e p f a c t o r : " ;s t d : : c i n >> d ;s t d : : c o u t << " I n p u t number o f s t e p s : " ;s t d : : c i n >> n ;

s t d : : c o u t << S0 [ 0 ] [ 0 ] << s t d : : e n d l ;

f o r ( c t r 1 = 1 ; c t r 1 <= n ; c t r 1 ++){

/ / p r i n t f i r s t p r i c e i n t h e l i n eS0 [ c t r 1 ] [ 0 ] = S0 [ c t r 1 −1] [0]∗ u ;

Page 18: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

316 A C/C++ Programming Tutorial

s t d : : c o u t << S0 [ c t r 1 ] [ 0 ] << " " ;

/ / each s u b s e q u e n t p r i c e i s t h e p r e v i o u s p r i c e t i m e s d / uf o r ( c t r 2 = 1 ; c t r 2 <= c t r 1 ; c t r 2 ++){

S0 [ c t r 1 ] [ c t r 2 ]= S0 [ c t r 1 ] [ c t r 2 −1]∗d / u ;s t d : : c o u t << S0 [ c t r 1 ] [ c t r 2 ] << " " ;

}s t d : : c o u t << s t d : : e n d l ;

}}

A.11 Functions

Apart from main(), we can create other functions. We can then call these functionswith a given set of inputs.

The function should be declared before we create it, similarly to how we declarevariables. For example, suppose that we want to create a function called factorial,which finds the factorial of a given integer greater than 1. It takes an integer greaterthan 1 as an input and returns the factorial of that integer.

The statement to return a value from a function is as follows:

r e t u r n v a l u e _ t o _ b e _ r e t u r n e d ;

We declare the function outside any other function, following the #includecommands, as follows:

i n t f a c t o r i a l ( i n t x ) ;

We can then create the function as follows:

i n t f a c t o r i a l ( i n t x ) {i n t r e t v a l , c t r ;r e t v a l =1 ;

f o r ( c t r =1 ; c t r <=x ; c t r ++){r e t v a l = r e t v a l ∗ c t r ;

}r e t u r n r e t v a l ;

}

We can call the function from another function such as main():

i n t main ( ) {i n t y ;

s t d : : c o u t << " I n p u t a whole number g r e a t e r t h a n 1 : " ;s t d : : c i n >> y ;

Page 19: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.11 Functions 317

s t d : : c o u t << " The f a c t o r i a l o f "<< y << " i s " << f a c t o r i a l ( y )<< s t d : : e n d l ;

}

In the main() function above, it would have been perfectly fine to use x instead ofy to hold the input value. This is inspite of the fact that we have another x inside thefactorial() function. The compiler knows to treat these as two different variables. Intechnical terms, each x lives only inside the particular function where it is defined.

Task

Rewrite findpv.cpp (use a new program findpv2.cpp) to use a function presentvaluethat finds the present value of a cashflow A at time n discounted at rate r withdiscounting k times per year.

Solution (findpv2.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

d o u b l e p r e s e n t v a l u e ( d o u b l e A, i n t n , d o u b l e r , i n t k ) ;

d o u b l e p r e s e n t v a l u e ( d o u b l e A, i n t n , d o u b l e r , i n t k ) {r e t u r n A / pow (1 + r / k , n∗k ) ;

}

i n t main ( ) {d o u b l e A, r ;i n t n , k ;

s t d : : c o u t << " I n p u t f u t u r e amount : " ;s t d : : c i n >> A;s t d : : c o u t << " I n p u t t ime t o m a t u r i t y i n y e a r s : " ;s t d : : c i n >> n ;s t d : : c o u t << " I n p u t APR d i s c o u n t r a t e ( a s a d e c i m a l ) : " ;s t d : : c i n >> r ;s t d : : c o u t << " Number o f compounding p e r i o d s p e r y e a r : " ;s t d : : c i n >> k ;

s t d : : c o u t << " P r e s e n t v a l u e i s "<< p r e s e n t v a l u e (A, n , r , k ) << s t d : : e n d l ;

}

Page 20: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

318 A C/C++ Programming Tutorial

A.12 Advanced Topics

The tasks in this section include a number of functions. It is convenient to enter allthese functions in the same file, that you could call say “myfunctions.cpp”. You caninclude a temporary main() function to call your functions after attempting each totest if your functions work.

A.12.1 The Standard Normal CDF

For many of our applications, we may wish to generate the standard normalcumulative distribution function, for which we use the notation Φ(z) in this book.The function Φ(z) gives the probability that a random variable following a normalcurve with mean 0 and standard deviation 1 (standard normal) is less than or equalto the number z.

We can derive the normal CDF using a related function available in C/C++ calledthe “error function” and written erf(x). We have the relationship:

Φ(z) = 1

2

(1 + erf

(z√2

))

TaskWrite a C/C++ function double phi (double z) that gives the standardnormal CDF.

Solution (phi)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h>

d o u b l e p h i ( d o u b l e z ) ;

d o u b l e p h i ( d o u b l e z ) {r e t u r n 0 . 5∗ ( 1 + e r f ( z / s q r t ( 2 ) ) ) ;

}

TaskWrite a function double normCDF (double x, double mu, doublesigma) that gives the probability that some normally-distributed variable is lessthan z, where the variable is distributed normally with mean mu and standarddeviation sigma. Hint: Use the fact that a normally distributed variable x with meanμ and standard deviation σ can be transformed to a standard normal variable Z(mean 0, standard deviation 1) as follows:

Z = X − μ

σ.

Page 21: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.12 Advanced Topics 319

It is convenient to call the previous function phi(...) in your answer. To do thiseasily, type the normCDF function in the same file where you typed phi.

Solution (normCDF)

d o u b l e normcdf ( d o u b l e x , d o u b l e mu , d o u b l e s igma ) ;

d o u b l e normcdf ( d o u b l e x , d o u b l e mu , d o u b l e s igma ) {r e t u r n p h i ( ( x − mu ) / s igma ) ;

}

A.12.2 The Inverse Normal CDF

We may also wish to generate some number z such that Φ(z) equals some valuesay p. We can define the function that finds z given p as the inverse standard normalCDF, and write it as Φ−1(p).

We can implement the standard normal CDF function in C/C++ using anapproximation correct to at least 3 decimal places that works as follows, if p isgreater than 0.5. (Formula source: Abramowitz and Stegun 1964)

Φ−1(p) = t − c0 + c1t + c2t2

1 + d1t + d2t2 + d3t3 ,

where:

t =√

ln1

(1 − p)2.

c0 = 2.515517.

c1 = 0.802853.

c2 = 0.010328.

d1 = 1.432788.

d2 = 0.189269.

d3 = 0.001308.

If p is less than 0.5, we can use the fact that the normal curve is symmetric. Sofor example Φ(−1.96) = 0.025, while Φ(1.96) = 0.975 = 1 − 0.025 (the regionto the right of 1.96 is the mirror image of the region to the left of −1.96, and hasthe same area). So if we are given p = 0.025, we can use the formula above to findΦ−1(0.975) = 1.96, and then stick a minus sign in front of the result to get −1.96.

Page 22: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

320 A C/C++ Programming Tutorial

TaskWrite a function double invphi (double p) that finds z = Φ−1(p) usingthe approximation given above. (If you get stuck trying to figure out how to dealwith cases where p < 0.5, try writing a program that only handles p ≥ 0.5. Thenyou can peek at the solution below to see one way to modify your program to handlethe general case.)

Solution (invphi)

d o u b l e i n v p h i ( d o u b l e p ) ;

d o u b l e i n v p h i ( d o u b l e p ) {d o u b l e t , c0 , c1 , c2 , d1 , d2 , d3 , r e t v a l ;

i f ( p > 0 . 5 ) {r e t v a l = 1 ;

}e l s e {

r e t v a l = −1;p = 1−p ;

}

t = s q r t ( l o g ( 1 / pow(1−p , 2 ) ) ) ;c0 = 2 . 5 1 5 5 1 7 ;c1 = 0 . 8 0 2 8 5 3 ;c2 = 0 . 0 1 0 3 2 8 ;d1 = 1 . 4 3 2 7 8 8 ;d2 = 0 . 1 8 9 2 6 9 ;d3 = 0 . 0 0 1 3 0 8 ;

r e t v a l = r e t v a l ∗ (t − ( c0 + c1∗ t + c2∗pow ( t , 2 ) ) /(1+ d1∗ t +d2∗pow ( t , 2 ) + d3∗pow ( t , 3 ) ) ) ;

r e t u r n r e t v a l ;}

TaskWrite a function double invnormcdf (double p, double mu,double sigma) that finds a number x such that a random number from anormal distribution with mean mu and standard deviation sigma has a probabilityequal to p of being less than or equal to x. You can call the previous function invphi,in which case, you would type invnormcdf in the same file as you used for invphi.

Page 23: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.12 Advanced Topics 321

Solution (invnormcdf)

doub le invno rmcdf ( doub le p , doub le mu , doub le s igma ) ;

doub le invno rmcdf ( doub le p , doub le mu , doub le s igma ) {r e t u r n i n v p h i ( p )∗ s igma + mu ;

}

A.12.3 Rounding

We can round a given double x to zero decimal places by using the functionround(x). For example:

round ( 3 . 6 ) / / g i v e s 4 . 0 .

To round x to say two decimal places, we can multiply x by 100 and then roundthe result, and then finally divide by 100 to get the desired number.

For example, if x = 1.23456, and we want to round to two decimal places, weuse:

round ( x ∗1 0 0 ) / 1 0 0 / / g i v e s 1 . 2 3 f o r x = 1 . 2 3 4 5 6 .

Similarly, to round to four decimal places, we multiply by 10,000 (104), round,and then divide by 10,000.

round ( x ∗10000) /10000 / / g i v e s 1 .2346 f o r x = 1 . 2 3 4 5 6 .

TaskWrite a function double roundn (double x, int n) that rounds a givendouble to n decimal places. (Hint: Use 10n).

Solution (roundn)

d o u b l e roundn ( d o u b l e x , i n t n ) ;

d o u b l e roundn ( d o u b l e x , i n t n ) {r e t u r n round ( x ∗ pow ( 1 0 , n ) ) / pow ( 1 0 , n ) ;

}

A.12.4 RandomNumbers

We may wish to generate random numbers, for example in Monte Carlo simulation.The C function to generate a random number is rand(). This gives a randomlygenerated positive integer (usually a very large integer).

By default, the random number generator would give us exactly the samesequence of numbers every time we run our program, which somewhat defeats thepurpose. To vary the sequence, we would change the “seed”, a parameter which therandom number generator uses in determining its output. The seed is also a positiveinteger.

Page 24: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

322 A C/C++ Programming Tutorial

To change the seed, we use the command srand (seed). For example tochange the seed to 64, we would use srand (64). In programs that generaterandom numbers, it is a good idea to reset the seed at or near the start of yourprogram, before generating any random numbers. It is possible to set srand() to usethe current system time as the seed, which guarantees a fresh random number everytime the program is run. But we will restrict ourselves to the cruder device of askingthe user to input some seed.

i n t s eed ;s t d : : c o u t << " I n p u t a seed f o r t h e random number g e n e r a t o r : " ;s t d : : c i n >> seed ;

What if we want random numbers that are between say 0 and 100? We can usethe modulus operator “%” to do this. Taking x % 101 would find the remainderfrom dividing a number by 101. This remainder would be a number between 0 and100. So to get a random number between 0 and 100, we would use:

r and ( ) % 101 ;

How about if we wanted a random number between say 100 and 200? We couldtake the random number modulus 101 (rand()%101) and add the starting 100 toit. In general, to find numbers between a and a +x, where a and x are both integers,we can take:

a + ( r and ( ) % ( x +1) ) .

What if we wanted our random numbers to be decimals? In particular, we maywant to generate decimals between 0 and 1 (to model random probabilities forexample).

To generate a random decimal between zero and 1 with 4 decimal places, wewould use (rand()%10001)/10000.0. This first generates a random integerbetween 0 and 10,000, and then divides by 10,000 to get a decimal between 0 and1. When dividing by 10,000, we should be careful to write it as 10000.0 to indicatethat we are dividing by a double, not an integer. Otherwise the program would givethe result as an integer, which would always be 0.

We are often interested in generating random numbers that follow a standardnormal distribution. How could we do this? One way is to first generate a randomprobability as described above. Then we could use our invphi(p) function to finda number z such that Φ(z) equals the random probability.

TaskWrite a function double simstdnorm() that simulates a random numberdrawn from a standard normal distribution. Create your function in the same fileas contains invphi, so that you can call on this function. Your function can assumethat srand() is already set.

Solution

doub l e s ims tdnorm ( ) ;

Page 25: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.12 Advanced Topics 323

doub l e s ims tdnorm ( ) {r e t u r n i n v p h i ( ( r and ( ) % 1 0 0 0 1 ) / 1 0 0 0 0 . 0 ) ;

}

TaskWrite a function double simnorm(double mu, double sigma) thatsimulates a random number drawn from a normal distribution with mean muand standard deviation sigma. Create your function in the same file as containsinvnormcdf, so that you can call on this function. Your function can assume thatsrand() is already set.

Solution

d o u b l e simnorm ( d o u b l e mu , d o u b l e sigma ) ;

d o u b l e simnorm ( d o u b l e mu , d o u b l e sigma ) {r e t u r n invnormcdf ( ( r and ( ) % 1 0 0 0 1 ) / 1 0 0 0 0 . 0 , mu , s igma ) ;

}

TaskThe Black-Scholes equation assumes the following:

Share prices S0+Δt at some incremental future step in time Δt years have thefollowing risk-neutral probability distribution:

ln

(S0+Δt

S0

)= ln S0+Δt − ln S0 ∼ N

((r − σ 2

2

)× Δt, σ × √

Δt

).

That is, the natural logarithm of the ratio of the future price S0+Δt at time Δt

to the price today S0 has a risk-neutral distribution that is normal (Bell curve) with

mean equal to (rc − σ 2

2 ) × Δt , and standard deviation equal to σ × √Δt . Here rc is

the risk-free rate, assumed constant, and σ is the volatility parameter.The same distribution holds for relative prices at additional increments of Δt .

Thus,

ln

(SΔt+Δt

SΔt

), ln

(SΔt+Δt+Δt

SΔt+Δt

), ... ∼ N

((r − σ 2

2

)× Δt, σ × √

Δt

).

where Sx is the price at some time x years from today.We can therefore simplify our notation by defining Δs as follows:

Δs = ln

(Sx+Δt

Sx

)= ln(Sx+Δt ) − ln(Sx).

where Sx is the price at any future time x years from today.We can summarize our exposition so far as:

Page 26: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

324 A C/C++ Programming Tutorial

Δs ∼ N

((r − σ 2

2

)× Δt, σ × √

Δt

).

Write a function double simdeltas(double rc, double sigma,double deltat) that simulates one instance of Δs given rc = rc, σ = sigma,and Δt = deltat. Your function can call simnorm.

Solution (simdeltas)

doub le s i m d e l t a s ( doub l e rc , doub l e sigma , doub l e d e l t a t ) ;

d o u b l e s i m d e l t a s ( d o u b l e rc , do u b l e sigma , d o u b l e d e l t a t ) {r e t u r n simnorm ( ( r c − pow ( sigma , 2 ) / 2 ) ∗ d e l t a t , s igma∗ s q r t ( d e l t a t ) ) ;

}

A.12.5 Your Own #include File

If you have typed in the various functions in this section in a file named say“myfunctions.cpp”, you can make them available to your programs written in otherfiles (in the same folder) by including the following line together with other #includecommands at the beginning of your file.

# i n c l u d e " m y f u n c t i o n s . cpp "

Depending on your system, you may need to give the full path of the file e.g.,“C:\...\myfunctions.cpp” on Windows. One quirk is that \has special meaning to theC compiler, so we have to represent a literal backslash by putting two backslashesin sequence. To type \, enter it as \\. For example the path C:\myhome \myfile.cppwould be written as follows in a C program:

C : \ \ myhome \ \ m y f i l e . cpp

You should make sure that the included file myfunctions.cpp does not includeany main() function. If you have included a temporary main() function to test yourfunctions, you should delete this main() function before including myfunctions.cppin other programs.

TaskWrite a program test.cpp that includes your function file containing the simdeltasfunction. Write a main() function that calls simdeltas to simulate and print out aprice history of 100 daily prices. Remember to set the random number seed at thebeginning of your program. The inputs to your program are the starting share priceS0, the risk-free rate rc, and the volatility parameter sigma. Recall that Δt for a dayis 1.0

365.0 years (keep the decimal points in this expression so that C/C++ treats this asa double not an int).

Page 27: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

A.13 Learning More 325

Solution (test.cpp)

# i n c l u d e < i o s t r e a m ># i n c l u d e <math . h># i n c l u d e " m y f u n c t i o n s . cpp "

i n t main ( ) {i n t seed , c t r ;d o u b l e mynormsim [ 1 0 0 ] , rc , sigma , S0 ;

s t d : : c o u t << " i n p u t random number seed : " ;s t d : : c i n >> seed ;s t d : : c o u t << " i n p u t r i s k −f r e e r a t e ( r c ) : " ;s t d : : c i n >> r c ;s t d : : c o u t << " i n p u t s t a r t i n g s h a r e p r i c e ( S0 ) : " ;s t d : : c i n >> S0 ;s t d : : c o u t << " i n p u t v o l a t i l i t y ( s igma ) : " ;s t d : : c i n >> sigma ;

s r a n d ( seed ) ;mynormsim [ 0 ] = S0 ;f o r ( c t r =1 ; c t r <100; c t r ++){

mynormsim [ c t r ]= mynormsim [ c t r −1]∗ exp ( s i m d e l t a s ( rc , sigma ,1 . 0 / 3 6 5 . 0 ) ) ;

s t d : : c o u t << mynormsim [ c t r ] << s t d : : e n d l ;}

}

A.13 LearningMore

The C/C++ covered in the tutorial so far is sufficient to do any of the programmingexercises in this book. But it does not go far enough to enable us to implement allthe models covered in our text. To do that, we would need to cover at least two moreprogramming topics for which we do not have space—date/time operations, and theimplementation of a solver function.

A more detailed C/C++ tutorial and reference is Prata (2011). A good tutorial onusing C++ in quantitative finance is Joshi (2008).

Quantlib is an extensive open-source library of C++ functions for quantitativefinance that can be found at http://www.quantlib.org. (It requires considerably moreadvanced knowledge of both C and C++ than what we can provide here.)

Page 28: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

BFinancial Math Refresher

B.1 Learning Outcomes

After finishing this appendix, you will be able to:

1. Explain exponential function and natural logarithm computations.2. Apply APR compound interest rates to find future values and present values.3. Derive and apply the formulas for future value and present value based on

continuous compounding.4. Convert between continuous and discrete (non-continuous) interest rates.

B.2 Euler’s Number

Consider the expression(

1 + 1n

)n

for some n ≥ 1.

As n gets larger and larger, this expression gets closer and closer to a constantknown as Euler’s number.

Euler’s number is written as e, and is approximately equal to 2.7182818...

Exercise 1. Try evaluating the expression(

1 + 1n

)n

for n=10, n=1,000, n=10,000,

n=100,000, n=1,000,000 ...

n (1 + 1n)n

10 2.593742

1000 2.716924

10000 2.718146

100000 2.718268

1000000 2.718280

© Springer Nature Singapore Pte Ltd. 2020S. Lynn, Valuation for Accountants, Springer Texts in Business and Economics,https://doi.org/10.1007/978-981-15-0357-3

327

Page 29: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

328 B Financial Math Refresher

B.3 The Exponential Function

Definition 1 (exponential of x or exp(x)). The exponential function exp(x) forany number x is given by:

exp(x) = ex.

Your calculator might show it as the EXP button or the ey button. In Excel,use=EXP(x)

Exercise 2 (Exponentials drill). Find e2, exp(2), e−1, exp(0).

Answer:

e2 = exp(2) = 7.3891.

e−1 = (1/e) = 0.3679.

Definition 2 (a−b). For any numbers a, b, we have:

a−b = 1

ab.

exp(0) = 1

Definition 3 (a0). For any number a, we have:

a0 = 1.

B.4 Natural Logarithms

Definition 4 (Natural logarithm of x or ln(x)). If ey = x then y is called thenatural logarithm of x.

Your calculator may show it as the LN button. In Excel, use =LN(x).

Exercise 3 (Logarithms drill). Find ln(1), ln(e), ln(2), ln(1,000,000), ln(−10),

ln(0.5).

Answer:

ln(1) = 0.

This follows because e0 = 1.

Page 30: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

B.5 Logarithm Arithmetic 329

ln(e) = 1.

This follows because e1 = e.

ln(2) = 0.69315.

ln(1,000,000) = 13.8155

Notice how very large numbers have relatively small logarithms. This is oftenconvenient in drawing graphs. By using a logarithmic scale, we can fit large andsmall numbers in the same graph.

ln(−10) is not defined.

There is no real number x such that ex = −10. The log of a negative numberdoes not exist.

ln(0.5) = −0.69315.

Notice that this is the negative of ln(2). Why?Why Is ln(0.5) = − ln(2)?

Proof.

0.5 = 1

2

This equals eln(1)

eln(2).

This equals eln(1)−ln(2).

(recalling index arithmetic from your secondary school maths)Therefore, ln(0.5) = ln(1) − ln(2) = 0 − ln(2).By similar logic, for any positive number a, ln(1/a) = −ln(a).

B.5 Logarithm Arithmetic

ln(xy) = ln(x) + ln(y).

Page 31: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

330 B Financial Math Refresher

Exercise 4 (Theorem on logs). Prove that:

ln(x/y) = ln(x) − ln(y). (B.1)

ln(xy) = y ln(x) (B.2)

Proof.Equation B.1

Take for example ln(3/2).

This can be written as: ln(

3 × 12

).

This equals: ln(3) + ln(0.5),which is the same as: ln(3) − ln(2).By similar logic, the result holds if we replace 3 and 2 by any positive numbers.

Equation B.2Take for example ln(34).This can be written as: ln(3 × 3 × 3 × 3) (multiplying three by itself 4 times).This equals: ln(3) + ln(3) + ln(3) + ln(3)

which is the same as: 4 × ln(3).By similar logic, the result holds if we replace 3 by any positive number and 4

by any natural number.The result holds for any power, not just natural numbers. We can prove this using

index arithmetic, noting that for any [real] numbers a, b, c, x, y:

(ab)c = ab×c ⇒

(eln(x)

)y = eln(x)×y.

B.6 APR Interest Rates

Definition 5 (APR or annual percentage rate convention). The annual percent-age rate convention for calculating compound interest is as follows: The future valueAt at the end of t years of a principal amount P earning compound interest at a rater per year, where the interest is compounded n times every year, is:

At = P ×(

1 + r

n

)t×n

Exercise 5 (Practice Drill). You lend CU39,247 at an interest rate of 3.83%compounded monthly, with principal and interest due at the end of 30 years. Howmuch interest will you earn over that period?

Page 32: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

B.8 Continuous Compounding at 100 Percent 331

Answer:

39,247 ×(

1 + 0.0383

12

)12×30

− 39,247 = 84352.35

The interest rate is always stated as a rate per year.

B.7 APR Discount Rates

Definition 6 (APR present value). The present value A0 of some amount P to bereceived after t years discounted at a rate r is:

A0 = P(1 + r

n

)t×n

Exercise 6 (Practice Drill). You face a risk-free opportunity to get CU97,387 atthe end of 6 years. You analyze the interest rates on government bonds, and estimatethat if the government offered a similar instrument with just one payment after6 years, it would pay interest at 1.89 percent compounded semi-annually (everyhalf-year). How much would you pay today for the risk-free investment?

Answer:

A0 = 97,387

/(1 + 0.0189

2

)6×2

= 86,993

B.8 Continuous Compounding at 100 Percent

Exercise 7. What is the future value of CU1 after one year if it is compoundedcontinuously at a rate of 100 percent? (Hint: recall the definition of e.)

Answer:The value is e.Consider for example CU1 compounded 1000 times per year at a rate of 100%.

The future value after 1 year is:(

1 + 100%1000

)1000.

As we keep increasing the frequency, to say n = 100,000 or 1,000,000 times per

year, the future value changes to:(

1 + 100%n

)n

.

This expression approaches e as n gets larger and larger (more frequent com-pounding). Therefore with the most frequent compounding possible (continuous),the value would be e.

Page 33: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

332 B Financial Math Refresher

B.9 Continuous Compounding at 5 Percent

Theorem 1. The continuously compounded future value of CU1 after one year atan interest rate of 5 percent is given by e0.05.

Proof (Sketch of proof). Let’s take e ≈ (1 + 0.0001)10,000.We can take CU 1 compounded continuously at 5% to approximately equal:(

1 + 0.05500

)500or (1 + 0.0001)10,000×0.05 or e0.05 (using our approximate expression

for e).The approximation gets better and better as we increase the compounding

frequency in the first equation.

B.10 Continuous Compounding for t Years

Exercise 8. You are investing CU30,000 for 6 years at a continuously compoundedrate of 3.067 percent. How much will you get on maturity?

Answer:The amount would be:

30,000 ×(e0.03067 × e0.03067 × e0.03067 × e0.03067 × e0.03067 × e0.03067

)

= 30,000 ×(e0.03067

)6

= 30,000 × e0.03067×6 = 36,061.20.

In general, the future value of CU Y earning compound interest at continuouslycompounded interest rate rc for t years is:

Yerct .

B.11 Continuous Discounting for t Years

Exercise 9. You want to buy an instrument that will pay you a total of CU30,000after 8 years, with no interim payments. If your required return is 5.4% continuouslycompounded, how much will you pay for the instrument?

Answer:Let the amount be X. Then

X × e0.054×8 = 30,000.

Page 34: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

B.11 Continuous Discounting for t Years 333

Therefore,

X = 30,000/

e0.054×8 = 19,476.28.

In general, the present value of CU Y discounted from year t to year 0 atcontinuously compounded interest rate rc is:

Ye−rct orY

erct.

Exercise 10. The monthly compounded interest rate is 6.95 percent. What is theequivalent continuously compounded rate? (Hint: Find the rate that gives the samepresent value for some fixed period, say 1 year).

Answer:Let the required rate be rc. Then:

erc =(

1 + 0.0695

12

)12

Taking natural logarithms on both sides:

rc = 12 ln

(1 + 0.0695

12

)= 6.93%

Exercise 11. The monthly compounded interest rate is 6.95 percent. What is theequivalent semi-annually compounded rate?

Answer: Let the required rate be rs . Equate future values of CU1 after 6 months.

(1 + 0.0695

12

)6

=(

1 + rs

2

)= 1.035257

Therefore,

rs = (1.035257 − 1) × 2 = 7.0514%

Exercise 12. The continuously compounded interest rate is 3.26%. What is the ratecompounded every 187 days? (Hint: that is, 365

187 times per year).

Page 35: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

334 B Financial Math Refresher

Answer: Let the required number be r . Equating future values after one year,

e0.0326 =(

1 + r

365187

) 365187

Rearranging, we get

r =(e0.0326× 187

365 − 1)

× 365

187= 3.287%.

References

Abramowitz, M., & Stegun, I. A. (1964). Handbook of Mathematical Functions with Formulas,Graphs, and Mathematical Tables (9th dover printing, 10th GPO printing edition). New York:Dover.

Joshi, M. (2008). C++ design patterns and derivatives pricing. Cambridge, UK: CambridgeUniversity Press.

Prata, S. (2011). C++ primer plus (6th ed.). New Jersey: Pearson Education.

Page 36: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

Index

Symbols30/360 convention (accrued interest), 84

AAccrued interest, 81, 84Actual/Actual (Act/Act) convention (accrued

interest), 85Adaptive weights, 276Adjusted present value (APV), 170Agriculture, 6American options, 15, 29, 36Amihud-Mendelsohn model, 232Annual percentage rate (APR) compounding,

75Arithmetic mean, 196Asian options, 15, 64Assembled workforce, 211Asset approach, 8

BBank discount rate, 73Bermuda options, 15, 32Beta, 191, 192Beta (guideline company), 192Binomial model, 16, 62Bisquare weights, 278Black-Derman-Toy (BDT) model, 92, 130Black-Scholes equation, 29, 35, 41Bond clean price, 81Bond dirty price, 81Bonds (callable), 130Bonds (convertible), 124Bonds (coupon), 78Bonds (puttable), 130Bonds (risky), 105Bonds (seasoned), 79

Bootstrapping, 86Bottom-up approach (NCI), 231, 234Build-up method, 199Business valuation, 137Business valuation (inputs), 177

CCallable bonds, 130Calls, 15Cap factor, 284Capital asset pricing model (CAPM), 191Cap rate, 284Cashflow to investors (CFI), 163Categorical variables, 261Clean price (bonds), 81Close-close volatility, 53Comparable transactions, 255, 257Continuous compounding, 74Convertible bonds, 124Cost approach, 8, 208, 255, 256, 290Cost of capital, 188Cost of debt, 189Cost of equity, 190Cost of equity (unlevered), 195Coupon bonds, 78Coupon bond terminology, 78Covered interest rate parity (CIRP), 100, 186Cox-Ross-Rubinstein (CRR) model, 22Credit rating (synthetic), 110Customer base, 216Customer base assets, 207Customer relationship asset, 216

DDCF model (1-stage), 150DCF model (2-stage), 151

© Springer Nature Singapore Pte Ltd. 2020S. Lynn, Valuation for Accountants, Springer Texts in Business and Economics,https://doi.org/10.1007/978-981-15-0357-3

335

Page 37: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

336 Index

DCF model (3-stage), 152Delta hedging, 17Direct capitalization, 256, 282Dirty price (bonds), 81Discount due to lack of control (DLOC), 232,

233Discount due to lack of marketability (DLOM),

232Discounted cash flow (DCF) valuation, 139,

149Discount factors, 72Discount margin (floater), 119Distance, 269Dividend discount model (DDM), 156Dividends (option models), 33Duplication cost new (DCN), 290Duration, 106Duration (Macaulay), 106Duration (modified), 106Dynamic hedging, 17

EEconomic decline, 292Employee stock options (ESOs), 4, 37Enterprise valuation, 137Enterprise value (EV) in ratios, 144Equal probabilities model, 25, 62Equity risk premium (ERP), 191, 196Euclidean norm, 257, 258European options, 15, 16EV/EBITDA (enterprise value to EBITDA),

147EV/sales (enterprise value to sales) ratio, 147Excess capital, 291Exotic options, 15Experience band, 220

FFair value, 2Fair value, definition, 6Fair Value hierarchy (IFRS 13), 6Financial instruments, 4, 11, 105Fixed maximum distance, 276Floaters, 117Floating rate notes (FRN), 117Flow-to-equity (FTE) model, 157Flow to equity (FTE), 157, 158Foreign currency cashflows, 186Forward discount factor, 76Forward exchange rate, 100Forward interest rates, 76Forward ratio, 140

Forwards, 11, 12Free cash flow (FCF), 161, 163, 164Fuller-Hsia H-model, 153Functional obsolescence, 292Futures, 14

GGarman-Klass volatility, 55Gaussian weights, 277Geodesic, 269Geographically weighted regression (GWR),

256, 267Geometric mean, 197Goldman-Sachs model (convertible bonds),

125Goodwill, 5, 138, 235Goodwill impairment, 205, 235Gordon growth model (GGM), 156Great circle, 269Gross income multiple (GIM), 282Guideline companies, 139, 200

HHarper-Lindquist model (NCI), 234Haversine distance, 272Hedonic valuation, 263Highest and best use, 253H-model, 153Ho-Lee (HL) model, 92, 96Hull-White ESO model, 42Human resource (HR) assets, 207, 211

IIAS 16, 3, 252IAS 32, 4IAS 36, 5, 238IAS 38, 5, 206IAS 40, 3, 252IFRS 13, 6IFRS 2, 4, 37IFRS 3, 5, 206IFRS 5, 253IFRS 7, 4IFRS 9, 4, 138IFRS and current value, 3Impairment, 5, 138, 235Impairment (goodwill), 205Implied equity premium, 198Implied volatility, 57Income approach, 8, 208, 255, 256, 281

Page 38: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

Index 337

Income normalization, 180Individual appraisal, 256Inputs (Business valuation), 177Intangibles, 5, 205International Capital Markets Association

(ICMA) convention, 81, 83International Swaps and Derivatives Authority

(ISDA) convention, 81, 82Interpolation (bootstrapping), 86Inutility, 291Investment property, 3, 252Iowa curves, 227Iteration, 167

JJarrow-Lando-Turnbull model, 111

KK nearest neighbors, 276

LLattices, multi-step, 20Legal claim, 206, 207Lifing, 219Linear interpolation (bootstrapping), 86L-type curves, 227

MMacaulay duration, 106Market approach, 7, 208, 255, 257Mass appraisal, 256Mid-year convention, 178Minkowski p-norm, 257, 262Modified duration, 106Monte Carlo simulation, 46, 64, 183Multi-period excess earnings model (MPEEM),

208, 215Multiple regression analysis (MRA), 255, 262,

265Multi-stage DCF model, 155

NNelson-Siegel model, 89Net operating income (NOI), 284Nominal spread, 107, 109Non-controlling interest (NCI), 231Norm, 257

OOne-stage DCF model, 150Options, 11, 14Option styles, 15Option types, 15Ordinary least squares (OLS), 256, 263O-type curves, 227

PParkinson High-Low (HL) volatility, 55Partial-year adjustment, 178Physical deterioration, 292Placements, 220Point spread, 107Price-earnings (P/E) ratio, 140Price-earnings-growth (PEG) ratio, 141Price-to-book (P/B) ratio, 142Price-to-sales (P/S) ratio, 140, 142Proforma financial statements, 179Projecting financial statements, 179Property, 251Property, plant and equipment (PPE), 3, 252Provisions, 6Purchase price allocation (PPA), 5, 138, 205,

227Put-call parity, 19Puts, 15Puttable bonds, 130Pythagorean distance, 271

RRatio-based valuation, 139Ratios, 140Ratios (forward), 140Ratios (trailing), 140Ratios (valuation ratios), 140Real estate, 251Recoverable amount, 3Reference rate (floater), 118Relief from royalty, 208Remaining useful life (RUL), 220, 241Replacement cost, 208, 209, 211Replacement cost new, 291Replicating portfolio, 8Replicating portfolio (swap), 123Reset margin (floater), 118Residual income valuation, 173Retirements, 220Risk-free rate, 188Risk-neutral probabilities, 18, 59Risky bonds, 105R-type curves, 227

Page 39: C/C++ProgrammingTutorial A978-981-15-0357-3/1.pdf · C/C++ is a commonly used computer programming language. C++ is an extra layer on top of an older language called C. We will not

338 Index

SSAB 107, 41SAB 110, 41Sanity check (PPA), 229Seasoned bonds, 79Semi-annual compounding (APR), 75Separability, 206, 207Software, 209Spot exchange rate, 100Spot interest rate, 75Spread, 107Spread (nominal), 107, 109Spread (Z-spread), 107, 108Strips, 72Stub curve, 220S-type curves, 227Sum of the parts, 160Svensson model, 88Swaps, 123Synthetic credit rating, 110

TTax amortization benefit (TAB), 218Three-stage DCF model, 152Tobin’s Q, 147Top-down approach (NCI), 231Trailing ratio, 140Transition matrix, 111Trinomial model, 26Two-stage DCF model, 151

VValuation approaches, 208, 255Valuation approaches (IFRS 13), 7Valuation hierarchy, 257

Valuation ratios, 140Value drivers, 180Value in use (VIU), 3, 237Vanilla options, 15Vesting, 38Vincenty inverse formula, 273Volatility, 20, 51

close-close, 53Garman-Klass, 55historical, 51implied, 57Parkinson High-Low, 55

WWACC-WARA comparison, 229Warrants, 14Weibull curve, 220Weighted average cost of capital (WACC), 166Weighted average return on assets (WARA),

229Weights, 259, 275With and without, 208, 214Workforce (assembled workforce), 211

YYield capitalization, 256, 286Yield conventions, 73Yield to maturity, 73

ZZero-coupon bonds, 72Zeroes, 72Z-spread, 107, 108


Recommended