B05 Answer


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

/* Puzzle B05 -- graph a histogram of N random
|                numbers in the range 0..9
|
*/
const int limit = 500 ;
const int maxPlus = 10 ;

int histo[] = {0,0,0,0,0,0,0,0,0,0};

/* Generate the random numbers and histogram them. */
void generate()
{
  int j, r ;

  for ( j=0; j<limit; j++ )
  {
    r = rand()%maxPlus ;
    histo[r]++ ;
  }
}

/* Find the maximum of all the histogram bins */
int findMax()
{
  int j;
  int max = histo[0];

  for ( j=1; j < maxPlus; j++ )
  {
    if ( histo[j] > max )
      max = histo[j];
  }
  
  return max;
}

/* Plot the histogram */
void plot ( int max )
{
  const int barWidth = 50;
  int j, s;

  for ( j=0; j<maxPlus; j++ )
  {
    printf("%3d (%5d):", j, histo[j] );
    for ( s=0; s<histo[j]*barWidth/max; s++ )
      printf("*");
      
    printf("\n");
  }
}

int main(int argc, char *argv[])
{
  int max;
  
  srand( time(NULL) );
  generate();
  max = findMax();
  plot( max );
  
  system("pause");	
  return 0;
}

Comments: The number of stars to print for a particular histogram value is computed by the expression:

histo[j]*barWidth/max;

where barWidth is the number of stars that spans the page and max is the maximum value in the histogram. Integer math is used, so you need to be careful that the * operation is performed before the / operation. This is so, because * and / have equal precedence and associate left to right.

You might not like how the array is a global. If you want, make it a local variable of main(), and pass it as a parameter to the three other functions.

Try increasing limit to larger and larger values. What is the effect on the histogram?


back