I am trying to determine why writing random values to an array is causing a problem.
I actually ask rand() to generate numbers between 1 and 10(rand() %10 +1, with srand(time(NULL)) before) and the first value is ALWAYS higher than 10: it’s a random one too, between 10 and 20. I really do not know how to fix that, as it looks like an issue with the rand and srand functions. Nevertheless this is my code:
Edit: correct code, now
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZEA 100
#define SIZEFREQ 10
int main()
{
int a[SIZEA]={0},frequency[SIZEFREQ]={0};
int i,temp,gothrough;
srand(time(NULL));
for(i=0;i<=SIZEA-1;i++)
{
a[i]=rand() %10 +1;
++frequency[a[i]-1];
}
printf("These are the elements in the vector:\n");
for(i=0;i<=SIZEA-1;i++)
{
printf("%3d,",a[i]);
}
printf("\nLet's try to put them in order\n");
for(gothrough=0;gothrough<=SIZEA-1;gothrough++)
{
for(i=0;i<=SIZEA-2;i++)
{
if (a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
for(i=0;i<=SIZEA-1;i++)
{
printf("%3d,",a[i]);
}
printf("\n\nValue Frequency\n");
for(i=0;i<=SIZEFREQ-1;i++)
{
printf("%5d%10d\n",i+1,frequency[i]);
}
return 0;
}`
The reason is simple.
a[i]is between 1 and 10 and therefore when you write:you are filling indices 2 to 11 of
frequency. However,frequencyhas only indices 0 to 10. Therefore you are going over the arrayfrequencyand into the arrayaand writing overa[0]. This happens whena[i]is 10. Since with 100 numbers, there is 10% chance you get 10, you incrementa[0](by incrementingfrequency[11]) about 10 times. Since the first value was also between 1 and 10, the final value gets between 10 and 20.Edit: For the same reason you index
afrom 0 toSIZE-1, you should also indexfrequencyfrom 0 to 10. What you are doing is to create indices from 1 to 10, and also +1 them! For example this here:should be
Notice both starting from 0, not going to 10, and indexing
frequencybyirather thani+1Alternatively, you could have
that indexes
frequencybyi-1to make the index right.