Use C rand function to generate random number

Syntax

C rand function has the following syntax.

int rand(void);

C rand function is from header file stdlib.h.

Description

C rand function generates a sequence of pseudorandom numbers.

Each time it is called, an integer between zero and RAND_MAX is returned. RAND_MAX will be at least 32,767.

Example

Use C rand function to generate random number.


#include <stdlib.h>
#include <stdio.h>
// ww  w . j  a va2  s. c o  m
int main(void)
{
  int i;

  for(i=0; i<10; i++){
    printf("%d \n", rand());
  }

  return 0;
}

The code above generates the following result.


Seed a random number


#include <stdio.h>
#include <stdlib.h>
 /*from  www.  j a  v  a  2  s .co m*/
int main(){
    int x;
 
    int seed = 11;
   
    srand(seed);

    puts("Behold! 100 Random Numbers!");

    for(x=0;x<100;x++){
        printf("%d \n", rand());
    }
    return(0);
}

The code above generates the following result.





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h