My goal is to produce a program which can take a random number from the user (srand) and then feed it to a random number generator (rand) which then chooses 1000 iterations of a random number between 1 and 10. I then want to output how many of each number was seen (i.e. 7 appears 83 times, etc).
I’m able to printf 1000 numbers between 1 and 10 randomly after taking the initial digit from the user, but can’t figure out how to take this output and feed it to an array which can then be used to break down the information for printing. Can anyone please help?
#include <stdio.h>
#include <stdlib.h>
int rand1(void);
void srand1(unsigned int seed);
int main()
{
int rand_array[1000];
int count;
int start=1;
int end=10;
int number_var;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
int fives=0;
int sixes=0;
int sevens=0;
int eights=0;
int nines=0;
int tens=0;
int frequency[11];
int i=0;
unsigned seed;
printf("Please enter your choice for seed.\n");
printf("(between 1-10)");
while (scanf("%u", &seed) == 1)
{
srand1(seed);
for(i=0; i < 1000; i++)
{
rand_array[i]=rand1()%(end-start+1)+start;
frequency[rand_array[i]]++;
}
for(i = 1; i < 11; i++)
{
printf("There are %d %d's\n", frequency[i], i);
}
}
return 0;
}
int rand1(void)
{
static unsigned long int next = 1;
next = next * 1103515245 + 12345;
return (unsigned int) (next/65536) % 32768;
}
void srand1(unsigned int seed)
{
static unsigned long int next = 1;
next = seed;
}
You could have an array of size 10 (or 11), type integer, where each slot represents the number of times that number is generated. For example, slot 3 would represent the number of times you generated a 3. So try this:
Note: I did not really read through most of your existing code, so I’m not sure if you have any other issues.
Edit: Here is an example of the general idea.
Say you have some random numbers:
Your
frequencyarray starts at 0s:So now we loop over your random numbers, and increment the associated slot.
For example, we read the 5, now our frequency array is:
Then the 2:
Then the 4:
Then the 9:
Again
At the end:
Now we know how many of each number there are! Say we want to know how many 9’s there were, we just look at the 9th slot and we see that there were 2 of them.
Does this make more sense? This is much better than having 10 separate variables for each number, and then saying “if the number was a 1, increment my 1s variable, if it was a 2, increment the 2s variable”. Plus if you have, say, random numbers between 1 and 100 instead of 1-10, it will be much easier to adapt your code.