• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2262
  • Last Modified:

How do I use rand() and srand()

I have read about them but do not really understand how to implement them. Really all I want is an example (annotated) in using them to generate random numbers. For example print out a new 4 digit random number each time a program loops. I know the syntax:

int rand(void)
void srand(unsigned int seed)

how to I actually use these in a program?

Cheers

Jim
0
Jim2000
Asked:
Jim2000
  • 2
1 Solution
 
WynCommented:
Here from MS:
/* RAND.C: This program seeds the random-number generator
 * with the time, then displays 10 random integers.
 */

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

void main( void )
{
   int i;

   /* Seed the random-number generator with current time so that
    * the numbers will be different every time we run.
    */
   srand( (unsigned)time( NULL ) );

   /* Display 10 numbers. */
   for( i = 0;   i < 10;i++ )
      printf( "  %6d\n", rand() );
}


Output

    6929
    8026
   21987
   30734
   20587
    6699
   22034
   25051
    7988
   10104

=======================
Free to ask for furthur explanation

Regards
W.Yinan
0
 
WynCommented:
->. For example print out a new 4 digit random number each time a program loops.
=================================
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
   int i;
   int PROGRAMLOOP
   /* Seed the random-number generator with current time so that
    * the numbers will be different every time we run.
    */
   srand( (unsigned)time( NULL ) );

  for( int j=0;j<PROGRAM_LOOP;j++)
  for( i = 0;i <4;i++ )
      printf( "%6d\n", rand() );
}
===========================

Jim2000 , plz note that srand() should be used only one time before sequentially rand() calls.

Regards
W.Yinan
0
 
Jim2000Author Commented:
Cheers perfect
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now