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
Release: 2023-08-27 18:37:06
forward
1006 people have browsed it

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;
}
Copy after login

Output

You will see the following output −

1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421
Copy after login

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;
}
Copy after login

Output

You will see the following output −

1919778910
1203408690
1755813469
1976428341
37040990
1849384103
986990763
2040061815
391541163
1718314135
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template