How Do rand, srand, and sleep Functions Work in C Programming?

  • Thread starter Thread starter the_kool_guy
  • Start date Start date
  • Tags Tags
    Sleep
Click For Summary
The rand function in C generates pseudorandom integers ranging from 0 to RAND_MAX, while srand is used to seed the pseudorandom number generator to produce different sequences of random numbers. The sleep function is not part of the C standard library but is available in GNU libc for pausing program execution. To generate random numbers within a specific range, the modulus operator can be used, such as rand() % 6 for numbers between 0 and 5. Properly using srand at the start of a program ensures varied results in repeated calls to rand. Understanding these functions is essential for effective random number generation in C programming.
the_kool_guy
Messages
37
Reaction score
0
in C how can one use rand,srand and sleep functions...
also what type of random numbers are generated by rand & srand.?

thanks
 
Physics news on Phys.org
Last edited by a moderator:
MisterX said:
sleep is not a C standard library function, but it is in GNU libc. http://www.gnu.org/software/libc/manual/html_mono/libc.html#Sleeping"

rand will typically return a pseudorandom integer in the range 0 to RAND_MAX. srand is for seeding the pseudorandom number generator.


Never heard of sleep function before!

rand will return a integer in the range 0 to RAND_MAX in the form of for example:

int rnumber;
rnumber=rand()%6; ---->this will give you a random number between 0 and 5
rnumber=rand()%6+1; ---->this will give you a random number between 0 and 6

This is great, the problem with this function alone is that it just gives you back a number of a already non-changing seed, if I am not mistaken!
To constantly change the seed you need to implement something in the beginning which i don't really remember what it is!

Also srand() function is best for let's say, a study on the results of a average number that gets out of a dice!

I was writing one program to make that several times by calling a function a several number of times to get a very precise result!

But I am rusty in C languagem although I am studying a little this vacations!
 
Last edited by a moderator:

Similar threads

  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
Replies
8
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K
Replies
5
Views
5K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 9 ·
Replies
9
Views
8K
  • · Replies 1 ·
Replies
1
Views
4K