C Random Numbers
In this page:
Generating Numbers with rand()
rand(), declared in stdlib.h, returns a pseudo-random integer somewhere between 0 and the implementation-defined constant RAND_MAX each time it's called, generating numbers from an internal algorithm rather than any genuinely unpredictable physical source.
Example: Generating Numbers with rand()
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = rand();
printf("%d", n >= 0);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Setting the Seed with srand()
Without calling srand() first, rand() always starts from the exact same internal state and therefore produces the identical sequence of numbers on every single run of the program, which is useful for reproducible testing but not for anything meant to feel random to a user.
Example: Setting the Seed with srand()
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(1);
int n = rand();
printf("%d", n >= 0);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Randomizing with time()
Seeding srand() with the current system time, via srand(time(NULL));, is the standard way to make each run of a program produce a different sequence of random numbers, since the current time is different (and effectively unpredictable) every time the program starts.
Example: Randomizing with time()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int n = rand();
printf("%d", n >= 0);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Limiting Random Ranges
Applying the modulo operator to rand()'s output, such as rand() % 10, restricts the generated values to a smaller range (0 through 9 in this example), which is the usual technique for generating random numbers within specific bounds like dice rolls or array indices.
Example: Limiting Random Ranges
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(1);
int n = rand() % 10;
printf("%d", n >= 0 && n < 10);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Generating Random Floats
Dividing rand()'s integer result by the floating-point constant RAND_MAX produces a random decimal value between 0.0 and 1.0, which is the standard building block for generating random floats or percentages, or for scaling into any other custom floating-point range you need.
Example: Generating Random Floats
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(1);
double f = rand() / (double)RAND_MAX;
printf("%d", f >= 0.0 && f <= 1.0);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: