Generate a random array in C

Mitro picture Mitro · Dec 10, 2012 · Viewed 14.8k times · Source

I'm developing in C using OpenVMS, I've done a code that put in a 1001 (0-1000) elements array, 1000 (0-999) random numbers between 0 and 50. Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main(){
    int vet[1000], fre[50];
    int i;

    srand(time(NULL));

    for(i=0;i<1000;i++){
        vet[i]=(rand()%51);
    }

    for(i=0;i<1000;i++){
        printf("%d\n", vet[i]);
    }

    for(i=0;i<1000;i++){
        fre[vet[i]]=fre[vet[i]]+1;
    }

    for(i=0;i<51;i++){
        printf("The number %d  was generated %d times\n", i, fre[i]);
    }
}

When I show how much times each number was generated, I saw that the number 50 has a big number, sometimes more than double than others numbers, someone can help me?

SOLVED Code that works I must use srand() for now

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main(){
        int vet[1000], fre[51] = {0};
        int i;

        srand(time(NULL));

        for(i=0;i<1000;i++){
                vet[i]=(rand()%51);
        }

for(i=0;i<1000;i++){
printf("%d\n", vet[i]);
}

        for(i=0;i<1000;i++){
                        fre[vet[i]]=fre[vet[i]]+1;
        }

        for(i=0;i<51;i++){
                printf("The number %d  was generated %d times\n", i, fre[i]);
        }
}
[EOB]

Thank you all

Answer

Daniel Fischer picture Daniel Fischer · Dec 10, 2012
    int vet[1000], fre[50];


    for(i=0;i<51;i++){
            printf("The number %d  was generated %d times\n", i, fre[i]);
    }

Problem 1: You declare fre to have 50 elements, but you use 51.

Problem 2: fre isn't initialised.

int vet[1000], fre[51] = {0};

should give you reasonable output.