How is the random number generated using 'rand' function in C?

QuestionsQuestions8 SkillsProDec, 18 2025
0100

In C, generating a random number involves two main functions from the <stdlib.h> library: srand() and rand(). Here is how they work together in your code:

1. Seeding with srand()

Computers are deterministic, meaning they can't create truly "random" numbers. Instead, they use a mathematical formula to generate a sequence of numbers that look random.

srand(time(NULL));
  • srand stands for "seed rand."
  • time(NULL) gets the current system time (which changes every second).
  • By using the current time as a "seed," we ensure that every time you start the game, the sequence of numbers is different. Without this, the "random" number would be the same every time you ran the program!

2. Generating with rand()

Once seeded, you call rand() to get a number.

int secret_number = rand() % 10 + 1;
  • rand() returns a very large integer (between 0 and RAND_MAX, which is at least 32,767).
  • The Modulo Operator (%): We use % 10 to limit the range. rand() % 10 gives the remainder of the division by 10, resulting in a number between 0 and 9.
  • The Offset (+ 1): Since we want a number between 1 and 10, we add 1 to the result.

Summary of the logic:

Expression Possible Range
rand() 0 to 32,767 (or more)
rand() % 10 0 to 9
rand() % 10 + 1 1 to 10

Pro Tip:

If you want a random number between 1 and 100, you would simply change it to:

int number = rand() % 100 + 1;

Does the math behind the % (modulo) operator make sense for controlling the range?

0 Comments

no data
Be the first to share your comment!