You are on page 1of 36

Introduction to C++

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Thursday 7 October 2010

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Organisation
The course will always take place in the Econometrics Room, MSE, at the following times Thursday 7 October 9.30am - 12.30pm (3h) Thursday 14 October 9am - 12pm (3h) Thursday 21 October 9am - 12pm (3h) Thursday 28 October 9am - 12pm (3h) 2 more classes: TBA (23h) Final mark is roughly based on Attendance - 20% Participation in classes and practicals - 30% Final Project / Exam - 50%

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Course material online

Slides can be found on the course webpage: http://epi.univparis1.fr/08708852/0/che pagelibre&RH=epi-023&RF=epi-023-MM0002v2

Google EPI C++ or EPI Paris 1 C++ General questions can be sent to: kimiya.minoukadeh@gmail.com

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

C++ references

A very useful site: C++ Language Tutorial: http://www.cplusplus.com/doc/tutorial/ An easy-to-read book with many examples: C++ How to Program by Deitel & Deitel

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Contents

Why C++?

Simple code and other examples

Data Types and integer representation

Random numbers

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Simple code in MATLAB

In a high-level language such as MATLAB, code is often easy to write and contains few lines Code in MATLAB a = 1:10; b = The sum of integers from 1 to 10 is; disp(b); sum(a)
Output The sum of integers from 1 to 10 is 55

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Simple code in C++


Writing a similar code in C++ involves many more lines... #include <iostream> int main() { int a[] = {1,2,3,4,5,6,7,8,9,10}; char b[] = "The sum of integers from 1 to 10 is "; int sumSoFar = 0; for (int i = 0; i < 10; i++) { sumSoFar = sumSoFar + a[i]; } std::cout << b << sumSoFar; }
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

So why C++?

In a C++ code, we must specify the type of variables used (int, char,...) determine the maximum number of elements in list (array) put the core of the code in a function called main... For even a simple task, C++ code is often long. So why choose C++ over MATLAB or other programming languages?

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Programming Languages
1

Maple/Scilab/MATLAB: Interpreted languages


Interpreted to machine code at run-time Slow execution Portable

Java: Semi-compiled language


Code semi-compiled to byte-code. Interpreted to machine code by JVM (Java Virtual Machine) Allows for applications on multiple platform, heterogeneous, distributed networks Still slow execution due to overhead of interpretation

C/C++: Compiled languages


Code is compiled directly to machine code, contained in les called executables Fast execution Machine dependent

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

C++ in Finance

C++ is a programming language of choice when one needs fast execution


nancial pricers

long simulations involving many iterations


Markov Chain Monte Carlo

to handle large data sets


via dynamic allocation, discussed later

to divide up parts of the project


via object oriented features, discussed later

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

C++ Compilers

In order to run C++ code, it will rst need to be compiled using a C++ compiler. Unix-like/Linux systems
GCC (GNU C compiler) for C++, called g++.

Windows
IDE (Integrated Development Environment) such as Microsoft Visual C++ (license needed) or DevC++ (free).

Mac OS X
IDE such as Xcode (normally already installed).

We will be using DevC++, already installed in the Econometrics Room.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Why C++?

Simple code and other examples

Data Types and integer representation

Random numbers

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

First program
helloworld.cpp 1. #include <iostream> 2. using namespace std; 3. 4. int main() 5. { 6. cout << "Hello World!" << endl; 7. return 0; 8. }
1. Directive to preprocessor: include the header le iostream 4. The funtion main() contains the main body of the program 6. std::cout is the standard ouput stream 6. std::endl inserts a new-line character
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

What it all means..


1. Directive to preprocessor: include the iostream standard le (header le given in the standard C++ library) 2. Elements of the standard C++ library are declared within the std namespace. 4. The funtion main() contains the main body of the program. All C++ programs must have one (and only one) main function. 4. The word main is followed in the code by parentheses (). This is what distinguishes a function declaration from other types of expressions in C++. A list of parameters may also be given. 5-8. The body of the main function is enclosed in braces {} 6-7. These are C++ statement; they must end with a semicolon ; 6. std::cout is the standard ouput stream (usually screen) 6. std::endl inserts a new-line character 7. The return statement causes the main function to nish. return 0 means the program worked as expected (with no errors)
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

Using variables
Data may also be stored in variables. A variable must have an identier to distinguish it from others
no variable may have the same name as another a valid identier is a sequence of one or more letters, digits or underscore characters ( )

have a type associated to it (character, integer,...)


primitive data types: char, int, double, short int, long int,...

be declared before it is used.


The declare a new variable: write the specier of the data type, followed by a valid variable identier int a, b; int c = 10; double d = 0.1;

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Data Types

Declaring variables int a; // declaring an integer int i = 1; // declaring + initializing integer a = 3.2; // Beware! a = floor(3.2)

char c = h; char st1[] = "Hello World!"; // array of (13+1) chars char st2[30]; // if to be initialized later

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Example 1. User input


user input.cpp 1. #include <iostream> 2. using namespace std; 3. 4. int main() 5. { 6. char name[30]; 7. cout << "Hello, please enter your name: "; 8. cin >> name; 9. cout << "Welcome, " << name << "!" << endl; 10. return 0; 11.} 6. maximum size of array must be determined at declaration 8. std::cin is the standard input stream
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

Operators
Assignment operator (=): int a, b; a = 5; b = 10; Arithmetic operators ( +, -, *, /, % ): a = a*b; a = b%2; Compound operators (+=, -=, *=, /=, %=)
a a a a += b; -= 5; /= b; *= b; a a a a = = = = a a a a + b; - 5; / b; * b;

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

More operators
Relational and equality operators ( ==, !=, >, <, >=, <=). The result of a relational operation is a Boolean value (true or false) (7 == 5) // evaluates to false. (5 > 4) // evaluates to true. ((a*b) != 2) // ... The assignment operator (=) and the equality operator (==) should not be confused! Logical operators ( !, &&, || ). The operator ! is the C++ operator to perform the Boolean operation NOT. !false !(5 == 5) (0 <= 4 || 10 < 2) // evaluates to true // evaluates to false // evaluates to true

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Conditional structures
The if/else statement if (condition) { statements1 } else { statements2 } The two may be concatenated to test a range of values code extract if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; The braces {} must be added when there is more than one statement per if/else clause.
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

Iteration structures
The for loop for (initialization; condition; increase) {statements}
code extract int N = 10; int array[N]; for (int i=0; i<N; i++) { array[i] = i*i; cout << array[i] << " "; } cout << endl; What is the output?

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Iteration structures
The while loop while (expression) {statements} code extract int val = 6; int guess; bool found = false; cout << "Guess a number between 1 and 10: "; while (!found) { cin >> guess; if (guess != val) cout << endl << "Try again: "; else found = true; } cout << "Well done! The number was " << val << endl;
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

Practical Assignment

Practical Assignment 1 Exercise 1

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Header les
The C++ standard library provides many functionalities, whose prototypes are given in various header les. The header les provide function prototypes and various data types and constants used by the library. Some examples are.. Header le <iostream> <cctype> <cmath> <ctime> <fstream> Description Standard input/output functions Functions for testing characters Math library functions Manipulating the time and date Input/ouput to les on disk Examples cout, cin islower() exp(), pow() time() open(), close()

There are many more.. check before writing your own functions.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Example 2. Transforming text


lower upper.cpp #include <iostream> // for std::cout #include <cctype> // for islower() and toupper() int main () { int i=0; char c; char str[]="Test String.\n"; while (str[i]) { c=str[i]; if (islower(c)) c = toupper(c); std::cout << c; i++; } return 0; } Output: TEST STRING.
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

Why C++?

Simple code and other examples

Data Types and integer representation

Random numbers

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

How are data types stored?


In computers, data are represented in sequence of bits (0s or 1s). Depending on the type of a variable, a certain amount of space (number of bits) is reserved in memory. Recall that 1 byte = 8 bits. Type char short int int long int double # bytes 1 2 4 4 8 Range of acceptable values 0 to 127 -32 768 to 32 767 -2.14 109 to 2.14 109 -2.14 109 to 2.14 109 -1.7 1038 to 1.7 1038 In powers of 2 0 to 27 -1 -215 to 215 -1 -231 to 231 -1 -231 to 231 -1

For char representation look up the ASCII table.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

More on integer types


Representation of signed numbers (twos complement arithmetic) 73 -126 0 1 1 0 0 0 0 0 1 0 0 0 0 1 1 0

Why? Each bit is multiplied by a power of 2: 27 26 25 24 23 22 21 20

So, if the nth bit in the sequence has value bn {0, 1}, then
N2

x=
n=0

2n bn

2N1 bN1

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

More on integer types

In the framework of 8-bit twos complement arithmetic, x = 127 would be represented as 0 1 1 1 1 1 1 1

What would be result of x+1? What is the binary representation of -1? Use unsigned integers or double for a wider range of numbers.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Why C++?

Simple code and other examples

Data Types and integer representation

Random numbers

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Random Numbers
Include header le <cstdlib> To generate a random number use function rand() The number is drawn uniformly between 0 and RAND MAX In fact, these random numbers are generated by a pseudorandom number generator: an algorithm for generating a sequence of numbers that approximates the properties of random numbers. Algorithm Given a, b, m > 0 and a seed x0 , the recurrence xn+1 = (a xn + b) mod m is used to generate the sequence of random numbers.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Example 3. Random Numbers


random number.cpp #include <iostream> #include <cstdlib> // needed for rand() using namespace std; int main() { double myrand; for (int i = 1; i < 5; i++) { myrand = (rand()/(double)RAND_MAX)*100; cout << myrand << endl; } }
Kimiya Minoukadeh kimiya.minoukadeh@gmail.com Introduction to C++

The random seed


You may change the seed of the random number generator by using the srand() function.
random number2.cpp #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand ( time(NULL) );

// gets current time

for (int i = 0; i < 5; i++) cout << (rand()/(double)RAND_MAX)*100 << endl; }

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Repeating sequence

With the random number generator, the sequence eventually repeats itself. For long simulations (e.g. Monte Carlo) where true randomness is important, one can use a larger modulus m. C++ provides a function drand48() where m = 248 . Mersenne twister (1997) is another random number generator, where m = 219937 . The Mersenne Twister package is freely available for C++.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

The normal distribution


The Box-Muller transform is a method of generating pairs of independent standard normally distributed random numbers, given a pair of uniformly distributed random numbers. Box-Muller Transform Given u1 U(0, 1) and u2 U(0, 1), two independent, normally distributed random variables can then be calculated by: z1 = 2log(u1 )cos(2u2 ) and z2 = 2log(u1 )sin(2u2 )

The C++ code is given in boxmuller.cpp on the course website. It will be needed for Exercise 7 of the practical assignment.

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++

Practical Assignment 1

Kimiya Minoukadeh kimiya.minoukadeh@gmail.com

Introduction to C++