L-12 MCS 260 Mon 17 Sep 2001
Below is the full program we discussed in class.
/* L-12 MCS 260 Mon 17 Sep 2001 : investigation of random number distribution
In the program below we ask the user to give in how many times to
generate random numbers in the interval [0,100]. The program then
displays the random numbers in column of 10 numbers, where each
column is 4 characters wide.
If the random numbers are distributed "normally", then we expect that
the smallest random number converges to zero, the largest one goes to
100, and the average of the random numbers converges to 50.
With "converge" we mean that the number of random numbers generated
should be "sufficiently large" to see the effect.
Besides another illustration of C functions (we see how to call a
function once with and once without using the value on return)
and top down refinement, we illustrate the use of static variables:
minimum, maximum, and average are managed by the functions.
These values cannot be changed by the main program which adds to
the security of the program.
We also illustrate the assert, which is useful to assure the
correctness of a program.
Following are three functions which respectively remember the
current maximum, minimum and average : */
int update_max ( int n );
/* compares n with current maximum and returns new maximum */
int update_min ( int n );
/* compares n with current minimum and returns new minimum */
int update_avg ( int n );
/* updates the average of all numbers supplied so far */
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<assert.h>
#define MAXNUM 100
int main(void)
{
int n; /* number of random numbers */
int ran; /* a random number */
int i; /* used as variable in the for loop */
srand(time(NULL)); /* time as seed for random number generator */
printf("How many random numbers you want ? ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
ran = rand() % (MAXNUM+1); /* careful: brackets must be there! */
assert(ran >= 0 && ran <= MAXNUM);
/* interesting to see what happens if bounds are changed */
printf("%4d", ran);
if (i%10 == 9) printf("\n");
update_max(ran);
update_min(ran);
update_avg(ran);
}
if (i%10 != 9) printf("\n");
printf("The largest random number : %3d\n", update_max(-1));
printf("The smallest random number : %3d\n", update_min(MAXNUM+1));
printf("The average of the numbers : %3d\n", update_avg(-1));
return 0;
}
int update_max (int n)
{
static int maximum = 0;
if (n > maximum)
maximum = n;
return maximum;
}
int update_min (int n)
{
static int minimum = MAXNUM+1;
if (n < minimum)
minimum = n;
return minimum;
}
int update_avg (int n)
{
static int sum = 0;
static int cnt = 0;
if (n < 0) return sum/cnt;
sum += n;
return sum/++cnt;
}