C Language - Generate random values

December 2016


I want to generate a number between 0 and 4 (possible values: 0,1,2,3,4) that will be then stored in the "nbr" variable.
  • How to achieve the following using the rand () function?


Try this:
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <conio.h> 

int Random (int _iMin, int _iMax) 
return (_iMin + (rand () % (_iMax-_iMin+1))); 

int main (void) 
int iRandom; 

srand (time (NULL)); 
iRandom = Random (50,100); 
printf ("Random : %d", iRandom); 
return 0; 

Thanks to scoubidou944 for this tip.

Related :

This document entitled « C Language - Generate random values » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.