HI,
I need to create a random array of 500 numbers between 1 and 1000. I understand how to create an array of 500 numbers but I can't seem to make it random. Can anyone help me.
Thank You.
HI,
I need to create a random array of 500 numbers between 1 and 1000. I understand how to create an array of 500 numbers but I can't seem to make it random. Can anyone help me.
Thank You.
FAQ > How do I... (Level 1) > Generate random numbers?
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
I have the random array but I can't figure out how to make the numbers range from 1 to 1000.
here is the code.
Can Anyone Help?Code:#include<stdio.h> #include<stdlib.h> #define ARY_SIZE 500 int bldarray (int randN[]); void printArray(int data[], int size); int main(void) { int randN[ARY_SIZE]; int R; R = bldarray(randN); printArray(randN, ARY_SIZE); return(0); } int bldarray (int randN[]) { int i; int randNo; int h[ARY_SIZE] = {0}; for(i = 0; i < ARY_SIZE; i++) { do { randNo = rand() % ARY_SIZE; }while (h[randNo] == 1); h[randNo] = 1; randN[i] = randNo; } return; } void printArray(int data[], int size) { int i; int numP = 0; for(i = 0; i < size; i++) { numP++; printf("%d\n", data[i]); } return; }
Last edited by pinkpenguin; 11-15-2005 at 04:41 PM.
Try reading the whole FAQ entry that Dave pointed you to. There's a whole section that starts with "To generate numbers in a specific range, you have to use some simple maths."
If you understand what you're doing, you're not learning anything.
First, you'll want this:
And if you want a range of 1000, this will get you 0-999:Code:int main(void) { int randN[ARY_SIZE]; int R; srand(time(0));
Fix the things your compiler warns you about, too.Code:int bldarray (int randN[]) { int i; int randNo; int h[ARY_SIZE] = {0}; for(i = 0; i < ARY_SIZE; i++) { do { randNo = rand() % 1000; }while (h[randNo] == 1); h[randNo] = 1; randN[i] = randNo; } return; }
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*