Puzzle R1


Print N random integers, one per line

[E-2] Write a main() program that prints N random integers one per line. Write the integers to standard output. On a Windows machine, write the integers to the DOS window. Here is the output of one run of the program:

  4068
   213
 12761
  8758
 23056
  7717
 15274
 24508
  4056
 13304

Copy-and-paste the following program into a source file and finish it.

/* Puzzle R01 -- print N random integers */

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

int main(int argc, char *argv[])
{
  int j;
  int limit = 25;            /* Print this many random integers */
  unsigned int seed = 123;   /* Initializer for rand() */

  /* Use command line parameters if supplied */
  if ( argc == 3 )
  {
    limit = atoi( argv[1] );
    seed  = atoi( argv[2] );
  }

  /* Initialize the random number generator */
  srand( seed );

  /* Loop limit times, printing one random integer per iteration */
  . . . .

  printf("\n");
  
  return 0;
}

In this program, the limit and the seed are command line parameters (although default values are supplied). See the answer to puzzle L22 for an explanation of these.



Answer         Next Page         Previous Page Home