Write a program that tests the effectiveness of the rand() library function. Sta
ID: 3697209 • Letter: W
Question
Write a program that tests the effectiveness of the rand() library function.
Start by initializing 10 counters to 0. You should use an ARRAY of 10 integers to hold your counters.
Declare the array:
int counter[10];
Remember to call srand supplying a seed before the loop.(look at Program 5.17 in text for inspiration).
Then generate ten thousand pseudo-random integers
between 0 and 9. Each time a 0 occurs, increment counter[0]; when a 1 occurs, increment the counter[1] and so on.
Finally, display the number of 0s, 1s, 2s, and so on that occurred.
If rand() produced exactly the theoretical result, you should see 1000 for each counter.
Remember the law of large numbers in probability, if you bump up the count of numbers generated you should get closer to the theoretical limit of one-tenth of the time for each digit.
This needs to be done using DEV C++
Explanation / Answer
#include <iostream>
#include <ctime>
int main()
{
//SIZE is ten thousand and limit for store count values for respective integers
enum {SIZE = 10000, LIMIT = 10};
int array[LIMIT];
//initializes array to zero
for (int i = 0; i < LIMIT; ++i)
array[i] = 0;
std::srand(std::time(nullptr));
for (int i = 0; i < SIZE; ++i)
{
//storing random numbers in to temp variable
int temp = std::rand() % LIMIT;
//increment respective counter
array[temp] += 1;
}
//Displaying number of times occurring from 0 to 9
for (int i = 0; i < LIMIT; ++i)
std::cout << i << " occurs " << array[i] << " times ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.