User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:stdlib.h:rand

rand

    #include <stdlib.h>
    int rand(void);

Description

Generates a random Number

  <time.h> is for this example nessesary

rand C Sourcecode Example 1

/* 
 * rand example code
 * http://code-reference.com/c/stdlib.h/rand 
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /* for srand salt */
 
int main ( void )
{
 
  int i;
  /* initialize random generator */
  /* without srand, rand will generate only once random numbers */
  srand ( time(NULL) ); /* comment it out to see what happend */
 
  printf ("random number between 0 and 100: %d\n", rand() % 100);
 
  /* random number */
  for(i=0; i<=5; i++){
      printf("example %i, rand() = %d\n",i, rand());  
  }
  return 0;
}

output of rand example 1

  user@host:~/code-reference.com#  ./rand
  random number between 0 and 100: 34
  example 0, rand() = 1299618648
  example 1, rand() = 556251950
  example 2, rand() = 1934607721
  example 3, rand() = 1297432736
  example 4, rand() = 1147459184
  example 5, rand() = 1432106816
  
  <time.h> is for this example nessesary

rand C Sourcecode Example 2

This example will generate a random number between 2 given int numbers

/* 
 * rand example code
 * http://code-reference.com/c/stdlib.h/rand 
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int rand_between(int min, int max);
 
int main( void ) {
 
  srand(time(NULL));
  printf("rand between   5 -   42 : %d\n",rand_between(5,42));
  printf("rand between 800 - 1000 : %d\n",rand_between(800,1000));
  return 0;
}
 
int rand_between(int min,int max){ 
 
     return(rand()%(max-min)+min); 
}

output of rand example 2

  user@host:~/code-reference.com#  ./rand 
  rand between   5 -   42 : 36
  rand between 800 - 1000 : 923

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
c/stdlib.h/rand.txt · Last modified: 2024/02/16 01:04 (external edit)

Impressum Datenschutz