c random value in range code example

Example 1: how to create random integers from a specific range in c language

//How to create random integers within a specific range in C langauge. 

srand(time(0))
number = (rand() % (upper - lower + 1)) + lower
//upper = max number
//lower = least number

Example 2: rand in c return type

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

int main () {
   int i, n;
   time_t t;
   
   n = 5;
   
   /* Intializes random number generator */
   //srand((unsigned) time(&t));

   /* Print 5 random numbers from 0 to 49 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
   return(0);
}

Tags:

C Example