In this practical we will begin by printing a single random number to the
screen, and modify the code over a number of iterations to print a random
numbers until the user types 't' (which terminates the loop). Then, a random
number will be printed, once it's generated, if we determine, randomly,
that it should be printed. Initially, the odds of the event occurring will
be hard-coded, but then the program will be modified to accept the odds via
the command line. Finally, instead of printing the random numbers, we will
modify the program to store the random numbers (if we determine that they
should be stored), and then when the user terminates the loop (by typing
't'), all the stored random numbers will be printed to the screen.
The programs are not commented :-(, but if you have problems figuring out
what's happening, drop me a line.
Program to print a random number to the screen
Yup, it is as simple as this.
Print an infinite number of random numbers
Loop forever
Loop terminates if user enters 't'
The loop will pause for input in this version.
Change stdin stream to non-blocking
Now, the loop will not wait for user input, but will
instead continue to execute until input is detected. Note that the user
must still type a carriage return to force the operating system to pass
the input stream to the buffer that C will access.
Only print the random number if some random event occurs
The chances of the event occurring are represented as the odds (e.g., 20%
or 1:5) of it occurring. The odds will be hard-coded to begin with, and
the program is here. In the program, the odds are
represented as a ratio, rather than a percentage, but fiddle with the code
to make it work when the odds are represented as a percentage.
The program also prints the total number of random numbers generated, and
the number of random numbers actually printed, so that you can see what
happens as the odds change.
Pass the odds as a command line parameter
Although the assignment will take the odds of process creations, etc., from
a configuration file, in this example, the odds are passed to the C
program from the command line. Please see the notes for Lecture 7
for a more detailed explanation of what is happening.
Finally, store the random numbers in a linked list
Rather than printing the random numbers as they are generated, this version
of the program will store the random number in a linked list if some
random event occurs, otherwise the random number will be discarded. When
the loop terminates (as a result of the user typing a 't'), the program
will print all the numbers that have been stored in the linked list. We
will cover this version of the program next week, but in the meantime you
can still access it.