cours1

36
Introduction to C++ Kimiya Minoukadeh [email protected] Thursday 7 October 2010 Kimiya Minoukadeh [email protected] Introduction to C++

Transcript of cours1

Page 1: cours1

Introduction to C++

Kimiya [email protected]

Thursday 7 October 2010

Kimiya Minoukadeh [email protected] Introduction to C++

Page 2: cours1

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 (2×3h)

Final mark is roughly based on

Attendance - 20%

Participation in classes and practicals - 30%

Final Project / Exam - 50%

Kimiya Minoukadeh [email protected] Introduction to C++

Page 3: cours1

Course material online

Slides can be found on the course webpage: http://epi.univ-

paris1.fr/08708852/0/fiche pagelibre&RH=epi-023&RF=epi-023-MM0002v2

Google “EPI C++” or “EPI Paris 1 C++”

General questions can be sent to: [email protected]

Kimiya Minoukadeh [email protected] Introduction to C++

Page 4: cours1

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 [email protected] Introduction to C++

Page 5: cours1

Contents

1 Why C++?

2 Simple code and other examples

3 Data Types and integer representation

4 Random numbers

Kimiya Minoukadeh [email protected] Introduction to C++

Page 6: cours1

Simple code in MATLAB

In a high-level language such as MATLAB, code is often easy towrite 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 is55

Kimiya Minoukadeh [email protected] Introduction to C++

Page 7: cours1

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 [email protected] Introduction to C++

Page 8: cours1

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 chooseC++ over MATLAB or other programming languages?

Kimiya Minoukadeh [email protected] Introduction to C++

Page 9: cours1

Programming Languages

1 Maple/Scilab/MATLAB: Interpreted languages

Interpreted to machine code at run-timeSlow executionPortable

2 Java: Semi-compiled language

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

3 C/C++: Compiled languages

Code is compiled directly to machine code, contained in filescalled executablesFast executionMachine dependent

Kimiya Minoukadeh [email protected] Introduction to C++

Page 10: cours1

C++ in Finance

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

fast execution

financial 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 [email protected] Introduction to C++

Page 11: cours1

C++ Compilers

In order to run C++ code, it will first need to be compiled using aC++ compiler.

Unix-like/Linux systems

GCC (GNU C compiler) for C++, called g++.

Windows

IDE (Integrated Development Environment) such as MicrosoftVisual 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 EconometricsRoom.

Kimiya Minoukadeh [email protected] Introduction to C++

Page 12: cours1

1 Why C++?

2 Simple code and other examples

3 Data Types and integer representation

4 Random numbers

Kimiya Minoukadeh [email protected] Introduction to C++

Page 13: cours1

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 file 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 [email protected] Introduction to C++

Page 14: cours1

What it all means..

1. Directive to preprocessor: include the iostream standard file(header file given in the standard C++ library)

2. Elements of the standard C++ library are declared within the stdnamespace.

4. The funtion main() contains the main body of the program. AllC++ programs must have one (and only one) main function.

4. The word main is followed in the code by parentheses (). This iswhat distinguishes a function declaration from other types ofexpressions 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 finish. return 0means the program worked as expected (with no errors)

Kimiya Minoukadeh [email protected] Introduction to C++

Page 15: cours1

Using variables

Data may also be stored in variables. A variable must

have an identifier to distinguish it from others

no variable may have the same name as anothera valid identifier is a sequence of one or more letters, digits orunderscore 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 specifier of the datatype, followed by a valid variable identifierint a, b;int c = 10;double d = 0.1;

Kimiya Minoukadeh [email protected] Introduction to C++

Page 16: cours1

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 [email protected] Introduction to C++

Page 17: cours1

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 [email protected] Introduction to C++

Page 18: cours1

Operators

Assignment operator (=):

int a, b;a = 5;b = 10;

Arithmetic operators ( +, -, *, /, % ):

a = a*b;a = b%2;

Compound operators (+=, -=, *=, /=, %=)

a += b; a = a + b;a -= 5; a = a - 5;a /= b; a = a / b;a *= b; a = a * b;

Kimiya Minoukadeh [email protected] Introduction to C++

Page 19: cours1

More operators

Relational and equality operators ( ==, !=, >, <, >=, <=). Theresult 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++ operatorto perform the Boolean operation NOT.

!false // evaluates to true!(5 == 5) // evaluates to false(0 <= 4 || 10 < 2) // evaluates to true

Kimiya Minoukadeh [email protected] Introduction to C++

Page 20: cours1

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

elsecout << "x is 0";

The braces {} must be added when there is more than onestatement per if/else clause.

Kimiya Minoukadeh [email protected] Introduction to C++

Page 21: cours1

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 [email protected] Introduction to C++

Page 22: cours1

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 [email protected] Introduction to C++

Page 23: cours1

Practical Assignment

Practical Assignment 1Exercise 1

Kimiya Minoukadeh [email protected] Introduction to C++

Page 24: cours1

Header files

The C++ standard library provides many functionalities, whoseprototypes are given in various header files. The header filesprovide function prototypes and various data types and constantsused by the library. Some examples are..

Header file Description Examples

<iostream> Standard input/output functions cout, cin<cctype> Functions for testing characters islower()<cmath> Math library functions exp(), pow()<ctime> Manipulating the time and date time()<fstream> Input/ouput to files on disk open(), close()

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

Kimiya Minoukadeh [email protected] Introduction to C++

Page 25: cours1

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 [email protected] Introduction to C++

Page 26: cours1

1 Why C++?

2 Simple code and other examples

3 Data Types and integer representation

4 Random numbers

Kimiya Minoukadeh [email protected] Introduction to C++

Page 27: cours1

How are data types stored?

In computers, data are represented in sequence of bits (0’s or 1’s).

Depending on the type of a variable, a certain amount ofspace (number of bits) is reserved in memory.

Recall that 1 byte = 8 bits.

Type # bytes Range of acceptable values In powers of 2

char 1 0 to 127 0 to 27-1short int 2 -32 768 to 32 767 -215 to 215-1int 4 -2.14 ∗ 109 to 2.14 ∗ 109 -231 to 231-1long int 4 -2.14 ∗ 109 to 2.14 ∗ 109 -231 to 231-1double 8 -1.7 ∗ 10−38 to 1.7 ∗ 1038

For char representation look up the ASCII table.

Kimiya Minoukadeh [email protected] Introduction to C++

Page 28: cours1

More on integer types

Representation of signed numbers (two’s complement arithmetic)

73 0 1 0 0 1 0 0 1

-126 1 0 0 0 0 0 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

x =N−2∑n=0

2n · bn − 2N−1 · bN−1

Kimiya Minoukadeh [email protected] Introduction to C++

Page 29: cours1

More on integer types

In the framework of 8-bit two’s complement arithmetic, x = 127would 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 [email protected] Introduction to C++

Page 30: cours1

1 Why C++?

2 Simple code and other examples

3 Data Types and integer representation

4 Random numbers

Kimiya Minoukadeh [email protected] Introduction to C++

Page 31: cours1

Random Numbers

Include header file <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 pseudorandomnumber generator: an algorithm for generating a sequence ofnumbers 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 [email protected] Introduction to C++

Page 32: cours1

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 [email protected] Introduction to C++

Page 33: cours1

The random seed

You may change the seed of the random number generator byusing 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 [email protected] Introduction to C++

Page 34: cours1

Repeating sequence

With the random number generator, the sequence eventuallyrepeats 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 freelyavailable for C++.

Kimiya Minoukadeh [email protected] Introduction to C++

Page 35: cours1

The normal distribution

The Box-Muller transform is a method of generating pairs ofindependent standard normally distributed random numbers, givena pair of uniformly distributed random numbers.

Box-Muller Transform

Given u1 ∼ U(0, 1) and u2 ∼ U(0, 1), two independent, normallydistributed random variables can then be calculated by:

z1 =√−2log(u1)cos(2πu2) and z2 =

√−2log(u1)sin(2πu2)

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 [email protected] Introduction to C++

Page 36: cours1

Practical Assignment 1

Kimiya Minoukadeh [email protected] Introduction to C++