C Language - Generate random values


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.
Published by deri58. Latest update on October 17, 2012 at 09:01 AM by deri58.
This document, titled "C Language - Generate random values," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (https://ccm.net/).
Code::Blocks - Unable to compile source code
Install a library under Codeblocks for MinGW