- 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
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.
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
it generates 1,9,2,4,7 again and again
lets change the code with a for loop srand(i);
after running it again and again it is also generating a sequence again and again
now lets use srand(); two times in a program and see what happened
so change the value of srand() changing the random number.
- 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
time() function c++ code