San Diego State University logo
ME 203

Module 4.1 - Array Basics


In the virtual run of the program average0.c that we've animated in the Connect section, you'll notice some very nicely randomized numbers in very convenient sizes generated from the rand() function. This is very rarely the case in real life.

  • Take some time to compile and run average0.c yourself. How did the numbers generated by rand() differ from what we came up with in our virtual, animated Flash version?
  • Now, run the program again; did the 'random' numbers change from what they were during your first run?
  • Try running it again; did they change this time?

If they didn't (And they almost certainly did not; your mileage may vary depending on machine, operating system and C compiler) it's because the rand() function depends on a seed number to begin the generation of the random number, and each subsequent call to rand() will depend on the previous value.

So if the seed value is the same (And it will be for most system software configurations), the initial random number, and all subsequent generated numbers, will be the same. In addition, they will tend to be quite large, large enough to tax the 4 bytes assigned to integers, which can produce unpredictable results.

You can deal with both the problem of non-randomness between program runs and the sizes of the generated numbers using the srand() function and the MAX_RAND constant defined in the library stdlib.h.

  • MAX_RAND defines the maximum size the random number can be;
    • You can use this number and a Maximum size that you define yourself, as operands on the number generated by rand() to generate a number between 0 and your defined maximum.
  • srand(<seed>) redefines the seed number used to initiate rand(); if we base this on a constantly changing number (Say, the current time), then we can guarantee different results for each run of our program.

Give a try to changing average0.c so that it

  • generates different numbers for each program run,
  • constrained by a number you define,
  • using srand() in the mathlib.h library and MAX_RAND in the stdlib.h library.

In case you're pressed for time or sufficient motivation, take a look at average0Mod.c, and compile and run it to see one potential solution to this problem.

Continue to the Extend Section ->

Website by Joshua Bleier