Reputation: 25
Being new to C, I'm trying to become familiar with the random number generator. I know how to get a random number between a certain interval (Like 1 and 100), but I'm curious as to if it's possible to get a random number that's range is inside an array's elements? Would I use rand() for this? I tried searching for some answers online to this challenge, but came up short in finding a solution. An example, if I had an array:
Array[10] = {50,26,29,10,78,12,45,83,39,55};
And I wanted to create a random number that's ending value is a number in the array, how would I do this in C?
Upvotes: 1
Views: 68
Reputation: 391
Try to get a random index.
index = rand() % 10;
A[index] // This gets a random value in your range
Upvotes: 0
Reputation: 399793
Simply generate a random number that's an index into the array, and read out the number at that location.
const int index = rand() % (sizeof Array / sizeof *Array);
const int value = Array[index];
Note that using modulo like this doesn't give you the best random numbers, but it should work at least.
Upvotes: 2
Reputation: 36473
Just pick a random index and access it.
Array[rand() % 10];
Upvotes: 0