C - Generate random number with rand() function

Introduction

The rand() function generates random numbers.

A computer cannot generate truly random numbers. Instead, it produces what are known as pseudo-random numbers.

It requires the stdlib.h header file.

Demo

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

int main() /*from  w  ww. j  a v a2 s . co  m*/
{ 
int r,a,b; 

   puts("100 Random Numbers"); 
   for(a=0;a<20;a++) 
   { 
       for(b=0;b<5;b++) 
       { 
           r=rand(); 
           printf("%d\t",r); 
       } 
       putchar('\n'); 
   } 
   return(0); 
}

Result

The code uses a nested for loop to display 100 random values.

The rand() function generates the values.

The printf() function displays the values by using the %d conversion character, which displays int values.

Related Topic