Social Icons

3 June 2012

0 Generating random number in C++ - PART -1

To generate random numbers in C++ , one can use rand(),  srand(), random(), randomize() functions defined in <stdlib.h> header file.
Using rand() function:-
rand() produces a random number in the range 0 to RAND-MAX. RAND_MAX is defined in <stdlib.h>  which gives the maximum value returned by rand(). For example-

#include<stdlib.h>
#include<iostream.h>
int main()
{
  int rand_num,i;
  for(i=0;i<10;i++)
   {
     rand_numrand();
      cout<<rand_num<<"\n";
    }
  return 0;
}

Using srand() function:-
To generate different random number everytime ,use srand() function. The srand() function starts the random-number generator from a point that depends on the value passed to srand() as argument.Therefore to generate different random numbers everytime, start the generator with a truly variable value such as system time. For eaxmple-
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
int main()
 {
  int i,rand_num;
  unsigned int seedval;
  time_t t;
  seedval=(unsigned) time(&t);
  srand(seedval);
  for(i=0;i<10;i++)
  cout<<rand()<<"\n";
  return 0;
}

0 comments:

Post a Comment

Hey this is a test comment

Related Posts Plugin for WordPress, Blogger...