Home >Backend Development >C++ >What is the use of randomization and srand function in C language?

What is the use of randomization and srand function in C language?

WBOY
WBOYforward
2023-08-27 18:37:061044browse

What is the use of randomization and srand function in C language?

If we generate random numbers in a program, it is necessary to control the sequence of numbers. The

randomize() and srand() functions are used to seed the random number generator.

The process of assigning a starting number to a random number generator is called a seed generator.

  • randomize() uses the PC's clock to generate a random seed.

  • srand() allows us to specify the starting value of the random number generator.

Program

The following is a program about rand in C language:

Demonstration

#include<stdio.h>
int main(){
   // create same sequence of
   // random numbers on every time the program runs
   for(int i = 0; i<10; i++)
      printf(" %d ", rand());
   return 0;
}

Output

You will see the following output −

1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421

The following is the C program about srand:

Online Demo

#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int main(){
   // create different sequence of
   // random numbers on every time the program runs
   // It Use current time as seed for random generator
   srand(time(0));
   for(int i = 0; i<10; i++)
      printf(" %d ", rand());
   return 0;
}

Output

You will see the following output −

1919778910
1203408690
1755813469
1976428341
37040990
1849384103
986990763
2040061815
391541163
1718314135

The above is the detailed content of What is the use of randomization and srand function in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more