This program is a simple exercise in using functions, basic control structures, and I/O in C.
Your program will "drop balls" each of which will bounce randomly and land in a slot. There will be 21 slots (numbered from -10 to 10). Each ball will be dropped over the middle slot (number 0) and "bounce" 10 times. On each bounce the ball will move (randomly) either left or right (i.e. to the slot with one number lower or one higher). Notice that since there will be an even number of bounces the ball will always land in an even-numbered slot.
The program will ask the user for the number of balls to be dropped and accept the user's answer. If the user enters a value less than 1 and error message will be displayed and the program will continue asking until a value at least 1 is entered. The program will then drop the requested number of balls and count how many land in each slot. A histogram will be displayed showing how many balls landed in each slot (you need only draw histogram lines for even-numbered slots). Use lower case 'o' for points in the histogram -- each 'o' will represent one ball. The histogram should (roughly) present a bell curve representing a normal distribution. Running the program may give a display as follows:
A first run of the program:
How many balls to drop? -4
Must drop at least one ball
How many balls to drop? 0
Must drop at least one ball
How many balls to drop? 100
-10:
-8:
-6: o
-4: ooooooooo
-2: oooooooooooooooooooooo
0: ooooooooooooooooooooooooo
2: oooooooooooooooooooooo
4: ooooooooooooo
6: ooooooo
8:
10: o
A second run of the program:
How many balls to drop? 150
-10: o
-8:
-6: ooooo
-4: ooooooooooooooooo
-2: oooooooooooooooooooooooooooooooooo
0: oooooooooooooooooooooooooooooooo
2: oooooooooooooooooooooooooooo
4: oooooooooooooooooooooooo
6: oooooooo
8: o
10:
Your program must be well-commented (of course), show good programming style, use several functions, and have a short main(). Each function other than main() should have a function prototype.
You will use an int array, say int catch[21], to count the number of balls which fall into the various slots: catch[10] will hold the number of balls which fall into the middle slot, catch[11] the number in the slot to its right, catch[9] the slot one left of the middle, etc. To "drop" a ball you will initialize a counter to 10 (for the middle slot) and let it "bounce" 10 times. A bounce will randomly add or subtract 1 from this counter. After the 10 bounces the value in the counter will be the slot where the ball lands -- increment the corresponding position in catch[].
The following functions from the standard library will be useful:
Thus, the random number generator can be (somewhat randomly) seeded by
srand(time(0));
and then a random non-negative integer will be returned by each call to rand().