Question

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;
}`
Was it helpful?

Solution

The reason is simple.

a[i] is between 1 and 10 and therefore when you write:

++frequency[a[i]+1];

you are filling indices 2 to 11 of frequency. However, frequency has only indices 0 to 10. Therefore you are going over the array frequency and into the array a and writing over a[0]. This happens when a[i] is 10. Since with 100 numbers, there is 10% chance you get 10, you increment a[0] (by incrementing frequency[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 a from 0 to SIZE-1, you should also index frequency from 0 to 10. What you are doing is to create indices from 1 to 10, and also +1 them! For example this here:

for(i=1;i<=10;i++)
    printf("%5d%10d\n",i,frequency[i+1]);

should be

for(i=0;i<10;i++)
    printf("%5d%10d\n",i,frequency[i]);

Notice both starting from 0, not going to 10, and indexing frequency by i rather than i+1

Alternatively, you could have

for(i=1;i<=10;i++)
    printf("%5d%10d\n",i,frequency[i-1]);

that indexes frequency by i-1 to make the index right.

OTHER TIPS

I compiled your code and it generates between 1 and 10. There is NO way to get over range 0-9 (or 1 - 10 with +1) with % used, since as soon as it would reach 10, that would mean that the / would be 1 higher AND modulo would have to start again at 0. EDIT: You can't divide 30 by 10 and say it's 2 with a remainder 10, since this remainder would translate to +1 of 10ths, that is, 30 divided by 10 = 3 and remainder 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top