How to use rand, srand and time function cpp

How to use rand, srand and time function cpp
Di Posting Oleh : Simple Learning
Kategori : rand() random number examples srand() time()

This tutorial contains
  • rand(); srand() and time() concept and how to use these functions
  • srand() example with rand() with in a for loop
  • rand() srand() and time program code with for loop
Random numbers are not truly random why?
Computers actually cannot generate truly random numbers because they are not human. Computer follows some algorithms to generate random numbers to make it more random.

 rand() with srand() function
 rand() function is a function in header file stdlib.h which simply returns a random number.
 srand();
prototype:  void srand(unsigned int seed);Return type: void
Takes an unsigned int argument as seed for example srand(10); which simply changes the algorithm

Lets discuss it with code examples

srand(); will  just change the algorithm if we run the program again and again it will generate the same random number with a same pattern

like below program




#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand(10);
for(int i=1;i<=5;i++)
  cout<<rand()%10<<endl;
return 0;

}

it generates 1,9,2,4,7 again and again
lets change the code with a for loop srand(i);


#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
  for(int i=1;i<=5;i++){
  srand(i);
  cout<<rand()%10<<endl;
  }
return 0;
}

after running it again and again it is also generating a sequence again and again
like 1,5,8,1,4

now lets use srand(); two times in a program and see what happened

#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
  srand(1);
  int random_number=rand();
  cout<<random_number<<endl;
srand(2);
random_number=rand();
cout<<random_number<<endl;
return 0;
}

sample output
41
45

so change the value of srand() changing the random number.

time() function
  • This functime comes from a header file which is <ctime.h>
  • It simply allows us to get the system or computers current time in seconds
  • Its is very use full function with srand() we will call it within srand() and will get different random number every time because seconds value is changing  
for example this program is almost generating a random number

time() function c++ code


#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main()
{
srand(time(0));
  for(int i=1;i<=5;i++){
  cout<<rand()%10<<endl;
  }
return 0;
}


0 Response to "How to use rand, srand and time function cpp"

Post a Comment