lynx   »   [go: up one dir, main page]

Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

C Tutorial

C HOME C Intro C Get Started C Syntax C Output C Comments C Variables C Data Types C Constants C Operators C Booleans C If...Else C Switch C While Loop C For Loop C Break/Continue C Arrays C Strings C User Input C Memory Address C Pointers

C Functions

C Functions C Function Parameters C Scope C Function Declaration C Recursion C Math Functions

C Files

C Create Files C Write To Files C Read Files

C Structures

C Structures C Nested Structures C Structs & Pointers C Unions C typedef

C Enums

C Enums

C Memory

C Memory Management

C Errors

C Errors C Debugging C NULL C Error Handling C Input Validation

C More

C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators

C Projects

C Projects

C Reference

C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h>

C Examples

C Examples C Real-Life Examples C Exercises C Quiz C Compiler C Syllabus C Study Plan C Certificate

C Random Numbers


Random Numbers

In C, you can make random numbers with the rand() function, which is found in the <stdlib.h> library.

By default, rand() gives the same sequence of numbers each time you run the program. To get different results on every run, you can also use srand() to set a "starting point" (called a seed). Since you just learned about date and time, you can now use the current time as the seed (because it is always changing). For this, you include <time.h> in your program.


Basic Random Number

The function rand() returns a random integer.

Example

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

int main() {
  int r = rand();
  printf("%d\n", r);
  return 0;
}

Try it Yourself »

Note: If you run this program several times, you will see the same numbers each time. This is because we have not set a seed yet.


Seeding the Random Generator

To get different numbers every time you run the program, you must give rand() a starting point (seed).

You do this with srand(). A common trick is to use the current time as the seed, because the time is always changing:

Example

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

int main() {
  srand(time(NULL));  // seed with current time

  printf("%d\n", rand());
  printf("%d\n", rand());
  printf("%d\n", rand());
  return 0;
}

Try it Yourself »

Tip: Call srand() only once, at the start of main. Do not call it again inside a loop.


Random Number in a Range

Often you want numbers in a smaller range, like 0 to 9. You can do this by using the modulo operator %:

Example

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

int main() {
  srand(time(NULL));

  int x = rand() % 10;  // 0..9
  printf("%d\n", x);
  return 0;
}

Try it Yourself »


Real-Life Example: Rolling Dice

A common real-life use of random numbers is rolling a six-sided dice. We can simulate this by using rand() % 6 to get numbers from 0 to 5, and then add 1 to make the range 1 to 6:

Example

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

int main() {
  srand(time(NULL));

  int dice1 = (rand() % 6) + 1;
  int dice2 = (rand() % 6) + 1;
  printf("You rolled %d and %d (total = %d)\n", dice1, dice2, dice1 + dice2);

  return 0;
}

Try it Yourself »

Each time you run the program, you will get two random numbers between 1 and 6, just like rolling two dice in real life.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

Лучший частный хостинг