rand() and srand() in C


rand()

The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.

Here is the syntax of rand() in C language,

int rand(void);

Here is an example of rand() in C language,

Example

 Live Demo

#include <stdio.h>
#include<stdlib.h>
int main() {
   printf("%d
", rand());    printf("%d", rand());    return 0; }

Output

1804289383
846930886

srand()

The function srand() is used to initialize the generated pseudo random number by rand() function. It does not return anything.

Here is the syntax of srand() in C language,

void srand(unsigned int number);

Here is an example of srand() in C language,

Example

 Live Demo

#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
   srand(time(NULL));
   printf("%d
", rand());    srand(12);    printf("%d", rand());    return 0; }

Output

1432462941
1687063760

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements