Function that fills an Array with random integers(including negative)

Viewed 46

I want to fill an array with random integers from -10 to 10. My function looks like this:

int array(int a[], int n, int min, int max){

for(int i=0;i<n;i++){
    a[i]=(rand()%min);
    printf("%d ", a[i] );
}   

In main I have declared "min" to -10. But it does not really work, it still prints between 0 - 9. I have tried with +1 after min, then i get 10, but still no negative integers.

3 Answers

The number of possible number is max - min + 1, so that's what you want to mod by, giving you a number from 0 to max - min. Then you add min to that to give you a number from min to max.

a[i]=(rand() % (max-min+1) + min );

The % (modulus) operator divides two integer types and returns the remainder, which may be negative if the left operator is negative. However rand() does not return negative values. This is why no negative numbers are getting inserted. Try:

a[i] = (rand()%21) - 10; 

Also, make sure to return a value from your function. Perhaps int * makes more sense, if you're returning the array you generated.

Get a random number properly:

int random( int min, int max )
{
  int N = max - min + 1;
  int K = RAND_MAX - (RAND_MAX % N);
  int n;
  do n = rand(); while (n >= K);
  return (n % N) + min;
}

This function cannot give you random values in ranges with magnitude greater than RAND_MAX, and RAND_MAX is often fairly small (32,767). If you need a greater range, let us know.

Thereafter, apply the function to each element of your array:

void randomize_array( int a[], int n, int min, int max )
{
  while (n--) a[n] = random( min, max );
}

Keep separate operations separate. Randomizing an array has nothing to do with printing it. Print separately:

void print_array( int a[], int n )
{
  if (!n) return;
  printf( "%d", a[0] );
  for (int i = 1;  i < n;  i++)
    printf( " %d", a[i] );
  printf( "\n" );
}

Putting it all together:

#define sizeof_array(A) (sizeof((A)) / sizeof((A)[0]))

int a[20];

randomize_array( a, sizeof_array(a), -10, 10 );
print_array( a, sizeof_array(a) );
Related