Random numbers c++ class 11 and 12

sathah 127 views 11 slides Nov 29, 2019
Slide 1
Slide 1 of 11
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11

About This Presentation

random numbers in c++ basic understanding concepts


Slide Content

RANDOM NUMBERS IN C++

RANDOM NUMBERS in C++

Example: rand() function to generate numbers btwn 1 to 100

Output However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed. So, if we run the code again, we'll get the same sequence repeated as in the previous run .

To make a different sequence of numbers, we should specify a  seed  as an argument to a  srand ()   function. Eg : srand (98765); To generate a ever changing sequence, we need to feed something other than static integer to the argument of the  srand ()  function. need of srand () function

The best solution is to seed the  rand()  function using the current time as the argument to  srand () , by calling  time()  function from the standard C++ library, < time.h >. This returns the system time. Then, for portability, we cast as an integer type: eg : srand (( int ) time(0)); srand ()

Example : using srand ()

OUTPUT: using srand () 1 st run 2 nd run

Generating a random number with a specified range: The rand( ) function by default generates a number in range 0 to RAND_MAX. Now if you want to generate a number with our own specified range say 5 to 10 , then you can change the rand( ) as below: (rand( ) % U) + L (rand( ) % 10) + 5 or random( U-L +1) + L random(10-5+1) + 5 Generate random numbers

//Program to generate 5 random numbers in the range 5 - 14 //program is using randomize( ) and random( ) functions. #include < iostream.h > #include < stdlib.h > #include < conio.h > # include < time.h > int main() { int num,i ; randomize();      for( i =0;i<5;++ i )      {           num=random(14-5+1)+5 ; //num = random(U – L + 1) + L ;            cout <<num<<' ';       } getch (); } random() and randomize() functions

OUTPUT   randomize ( )  function internally implements a macro that calls time function of time.h . So, you need to use time.h header file in your program to implement random ( ) function.