Answer R4


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

/* Puzzle R04  -- histogram random integers in the range 0..9 */

const int limit = 100000000 ;

int main(int argc, char *argv[])
{
  int j, r;
  int histo[] = {0,0,0,0,0,0,0,0,0,0};
  int sum = 0;
  
  srand( time(NULL) );
  for ( j=0; j < limit; j++ )
  {
    r = rand()%10 ;
    histo[r]++ ;
    sum += r;
  }
  for ( j=0; j < 10; j++ )
  {
    printf( "%2d:  %8d\n", j, histo[j] );
  }
  printf("\n");	
  printf( "average = %8.5f\n", (double)sum/limit );
  return 0;
}

Comments: The program uses integer math to compute the random integers, as discussed in the previous answer. The average should be floating point, so sum is type cast to double. Another way to do this is to declare double sum = 0.0 at the top of the program.

Whenever you have a sum of some sort, initialize it to zero. Sometimes C compilers don't complain if you did not, and your results will be mysteriously wrong.



Back to Puzzle Home