Ad space (banner)
๐Ÿ”งC Lessons
Lesson 53 / 68

Generating Random Numbers

This lesson covers generating random numbers in C using the rand function, so you can build logic with a random element, like a dice roll or rock-paper-scissors. It's for anyone searching "C rand usage."

rand() generates a random number. Seeding the generator with srand(time(NULL)) gives you a different result every time you run the program.

The example generates a dice roll from 1 to 6 with rand() % 6 + 1, and picks one of "Rock, Scissors, Paper" at random with rand() % 3. Narrowing the range with the % operator is C's traditional way of generating a random number.

A common early mistake is forgetting to call srand(). Without it, the program produces the exact same sequence of random numbers every time it runs, and it won't look random.

In real projects, when higher-quality randomness is needed, a dedicated library is sometimes used instead of C's standard rand().

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)