← Back to C Course | Chapter 14: Additional Topics | Lesson 8 of 9

C Random Numbers

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()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int n = rand();
	printf("%d", n >= 0);
	return 0;
}

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()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	srand(1);
	int n = rand();
	printf("%d", n >= 0);
	return 0;
}

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()

c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
	srand(time(NULL));
	int n = rand();
	printf("%d", n >= 0);
	return 0;
}

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

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	srand(1);
	int n = rand() % 10;
	printf("%d", n >= 0 && n < 10);
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.