c++ programming lecture 10 functions – part ii by ghada al-mashaqbeh the hashemite university...

23
C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

Upload: rudolph-turner

Post on 05-Jan-2016

254 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

C++ ProgrammingLecture 10

Functions – Part II

ByGhada Al-MashaqbehThe Hashemite UniversityComputer Engineering Department

Page 2: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 2

Outline

Introduction. Random numbers generation in C+

+. enum data type identification and

usage. Examples.

Page 3: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 3

Random Number Generation I

Random number generation is used mainly in simulation and game playing based application.

The rand() function is used in C++ to generate random integer numbers between 0 and a maximum specified value.

rand() function takes nothing (i.e. void) as its arguments and returns an unsigned integer.

In order to use this function you must Load <cstdlib> or <stdlib.h>

Page 4: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 4

Random Number Generation II rand function syntax:

int i = rand(); Generates a pseudorandom number between 0

and RAND_MAX (usually 32767) RAND_MAX is a symbolic constant defined in the

stdlib header file. 0 <= rand() <= RAND_MAX. A pseudorandom number is a preset sequence

of "random" numbers. The same sequence is generated upon every

program execution, is this preferred?. This repeated behavior is essentially in

programming debug and verification in simulation and other random-based applications.

Page 5: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 5

Random Numbers Seeding I srand function

Jumps to a seeded location in a "random" sequence. Similar to rand() function, srand function is defined

in the <stdlib.h> library. Takes an unsigned integer as a seed (i.e. as an

argument). It does not return any value (returns void), it just

change the random sequence (randomizing the rand() function).

Can be called more than once within the same program.

Still you need to use the rand() function to get the random numbers.

Page 6: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 6

Random Numbers Seeding II

srand syntax:srand( seed );

seed can be any unsigned integer entered manually be the user or initialized through the program.

If the same seed is used every time the program is run we will get the same random sequence (i.e. the same without seed).

Page 7: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 7

Random Numbers Seeding III

To initialize seed value automatically use the following syntax:

srand( time( 0 ) ); time( 0 )

Returns the current calendar time in seconds. time() function takes a pointer as an argument and

returns unsigned integer. Changes the seed every time the program is run,

thereby allowing rand() to generate random numbers. So, it is much better than manual seeding.

Need to include the <ctime> or <time.h> library to use the time() function.

Page 8: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 8

Changing Random Numbers Range I

Scaling and shifting Reduces random number to a certain

range Modulus ( % ) operator

Reduces number between 0 and RAND_MAX to a number between 0 and the scaling factor:

Number = offset (shift value) + rand() % scaling_factor

Examplei = rand() % 6 + 1;

Generates a number between 1 and 6

Page 9: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 9

Changing Random Numbers Range II Scaling and shifting equations:

Lets assume the range is [min, max], then:Offset = min.Scaling factor = max – min + 1

Lets assume the range is [min, max) [min, max-1], then:

Offset = min.Scaling factor = max – min

Lets assume the range is (min, max][min+1, max], then:

Offset = min + 1.Scaling factor = max – min

Continue for other possibilities .....

Page 10: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 10

Changing Random Numbers Range III

All the previous equations are used to generate integers but what about floating point random numbers?

First: convert the floating point range into an integer range by multiplying the range by 10^n where n is at least the number of digits after the decimal point.

Second: find the values of both the offset and scaling factor based on the equations in the previous slide.

Third: divide the resulting random number on 10^n to get a floating point random number in the specified range.

Note that n controls the difference value (lets call it the step width) between the generated random numbers.

Page 11: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 11

Examples Generate random numbers in the following

ranges: 100 <= n <= 200 int n = 100 + rand()%101 100 <= n < 500 int n = 100 + rand()%400 50 < n <= 200 int n = 51 + rand()%150 100 < n < 200 int n = 101 + rand()%99 0.01 <= n <= 0.08

double n = (1 + rand()%8)/100 -- with step width = 0.01

0.02 <= n <= 0.9 double n = (20 + rand()%821)/1000 -- with step width

= 0.001

Page 12: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 12

1 // Fig. 3.7: fig03_07.cpp

2 // Shifted, scaled integers produced by 1 + rand() % 6

3 #include <iostream>

4

5 using std::cout;

6 using std::endl;

7

8 #include <iomanip>

9

10 using std::setw;

11

12 #include <cstdlib>

13

14 int main()

15 {

16 for ( int i = 1; i <= 20; i++ ) {

17 cout << setw( 10 ) << ( 1 + rand() % 6 );

18

19 if ( i % 5 == 0 )

20 cout << endl;

21 }

22

23 return 0;

24 }

Notice rand() % 6 . This returns a number between 0 and 5 (scaling). Add 1 to get a number between 1 and 6.

Executing the program again gives the same "random" dice rolls.

5 5 3 5 5 2 4 2 5 5 5 3 2 2 1 5 1 4 6 4

Page 13: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 13

1 // Fig. 3.9: fig03_09.cpp

2 // Randomizing die-rolling program

3 #include <iostream>

4

5 using std::cout;

6 using std::cin;

7 using std::endl;

8

9 #include <iomanip>

10

11 using std::setw;

12

13 #include <cstdlib>

14

15 int main()

16 {

17 unsigned seed;

18

19 cout << "Enter seed: ";

20 cin >> seed;

21 srand( seed );

22

23 for ( int i = 1; i <= 10; i++ ) {

24 cout << setw( 10 ) << 1 + rand() % 6;

25

26 if ( i % 5 == 0 )

27 cout << endl;

28 }

29

30 return 0;

31 }

Page 14: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 14

Program Output

Enter seed: 67 1 6 5 1 4 5 6 3 1 2

Enter seed: 432 4 2 6 4 3 2 5 1 4 4

Enter seed: 67 1 6 5 1 4 5 6 3 1 2

Notice how the die rolls change with the seed.

Page 15: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 15

Enumeration I

It is the counterpart of symbolic constants found in C (to assign integer values to symbolic constants).

The main difference is that enum can define a new data type within the program.

Enumeration - set of integers with identifiersenum typeName {constant1, constant2…};

Constants start at 0 (default), incremented by 1

Unique constant names

Page 16: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 16

Enumeration II If you don't specify values for enum constants, the values

start at zero and increase by one with each move down the list.

E.g:enum MyEnumType { ALPHA, BETA, GAMMA }; ALPHA has a

value of 0, BETA has a value of 1, and GAMMA has a value of 2.

If you want, you may provide explicit values for enum constants, as in enum Size { SMALL = 10, MEDIUM = 100, LARGE = 1000 };

Or enum Size { SMALL = 10, MEDIUM, LARGE }; //here MEDIUM will

have the value of 11 and LARGE will have the value of 12 You can assign positive and negative integer values to

enum constants (but not floating point values which will be a syntax error).

Page 17: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 17

Enumeration III There are two kinds of enum type declarations.

One kind creates a named type, as in enum MyEnumType { ALPHA, BETA, GAMMA }; If you give an enum type a name, you can use that type

for variables, function arguments and return values, and so on:

E.g:enum MyEnumType x; /* legal in both C and C++ */ MyEnumType y; // legal only in C++

The other kind creates an unnamed type. This is used when you want names for constants but don't plan to use the type to declare variables, function arguments, etc.

For example, you can write enum { HOMER, MARGE, BART, LISA, MAGGIE };

Page 18: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 18

C++ enum type conversion rules There is an implicit conversion from any enum

type to int. E.g:

enum MyEnumType { ALPHA, BETA, GAMMA }; Then the following lines are legal: int i = BETA; // give i a value of 1 int j = 3 + GAMMA; // give j a value of 5

On the other hand, there is not an implicit conversion from int to an enum type: MyEnumType x = 2; // syntax error MyEnumType y = 123; // syntax error

Page 19: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 19

Enumeration Example I#include<iostream.h>

int main(){

enum cars{BMW, MAZDA, KIA, BENZ};

cars mycar;int money, i,

BMW_price = 1000, MAZDA_price = 100,KIA_price = 500,BENZ_price = 2000;

cout << "Enter the car type (BMW = 0, MAZDA = 1, KIA = 2, BENZ = 3):\n";cin >> i;mycar = (cars)i;cout << "Enter the money balance:\n";cin >> money;

Page 20: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 20

Enumeration Example II

switch(mycar){case BMW:

if(money >= BMW_price)cout << "You cannot bye car " << mycar << endl;

elsecout << "You cannot bye car " << mycar << endl;

break;case MAZDA:

if(money >= MAZDA_price)cout << "You cannot bye car " << mycar << endl;

elsecout << "You cannot bye car " << mycar << endl;

break;

Page 21: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 21

Enumeration Example II case KIA:

if(money >= KIA_price)cout << "You cannot bye car " << mycar << endl;

elsecout << "You cannot bye car " << mycar << endl;

break;case BENZ:

if(money >= BENZ_price)cout << "You cannot bye car " << mycar << endl;

elsecout << "You cannot bye car " << mycar << endl;

break;}return 0;

}

Page 22: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 22

Example Output

Try it and find the output by your self.

Page 23: C++ Programming Lecture 10 Functions – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

The Hashemite University 23

Additional Notes

This lecture covers the following material from the textbook: Fourth Edition:

Chapter 3: Sections 3.8 and 3.9