loader

Loading

CoderrShyam logo

CoderrShyam

  • Home
  • About
  • Contact
  • Blog
  • Tutorials
    LoginSignup

How to Generate Random Numbers in C Language

Learn how to generate random numbers in C.

Back

In C, you can generate random numbers using two key functions:

  1. rand(): generates a random integer
  2. srand(): seeds the random number generator to vary the sequence

Method 1: Using rand()

The rand() function returns a pseudo-random integer. You can scale or mod it to fit a desired range.

main.c
#include <stdio.h>
#include <stdlib.h>

int main() {
  int random_number = rand();
  printf("Random Number: %d\n", random_number);
  return 0;
}

Since rand() produces a pseudo-random number, the same sequence will repeat on each execution unless you change the seed.

Method 2: Using srand()

The srand() function seeds the random number generator, typically with the current time, to ensure the random sequence varies on each program run.

main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
  srand(time(0));
  int random_number = rand();
  printf("Random Number: %d\n", random_number);
  return 0;
}

By using srand() with time(0), you get a fresh sequence of random numbers every time you run the program.

Conclusion

Using srand() and rand() together allows you to generate random numbers effectively in C.

  • rand() generates random numbers.
  • srand() seeds the random number generator for varied output.

Happy coding!

Written by

Shyam Verma

At

October 1st, 2024

March 7th, 2026

Read time

2 min

Tags

crandom-numbersprogrammingrandsrand
Follow us on GitHub
CoderrShyam logo

CoderrShyam

A professional web developer.

GithubTwitterBlue Sky

Resources

HomeAboutBlogContactTutorials

Socials

GitHubTwitterInstagramLinkedInFacebookThreadsBlue SkyStack OverflowReddit

Legal

Privacy PolicyTerms of Service

Authentication

ProfileLoginSignupForgot Password

© 2026CoderrShyamAll Rights Reserved.

CoderrShyam

Leave comment