C09 Answer
#include <stdio.h>
#include <stdlib.h>
/* Puzzle C09 -- fill an array with an ascending sequence of random integers */
int randInt( int min, int max );
void fillArrayRandomAscending( int arr[], int size, int maxStep )
{
int j;
arr[0] = randInt( 0, maxStep-1 );
for ( j=1; j<size; j++ )
arr[j] = arr[j-1] + randInt( 1, maxStep );
}
void printArray( int arr[], int size )
{
const int N = 10;
int j;
for ( j=0; j<size; j++ )
{
if ( j%N == N-1 )
printf("%4d\n", arr[j] );
else
printf("%4d ", arr[j] );
}
}
int randInt( int min, int max )
{
return (rand()*(max-min+1))/(RAND_MAX+1) + min ;
}
int main(int argc, char *argv[])
{
const int SIZE = 100;
int x[ SIZE ];
srand( time(NULL) );
fillArrayRandomAscending( x, SIZE, 10 );
printArray( x, SIZE );
printf("\n");
system("pause");
return 0;
}
Comments: It might sometimes be useful to fill an array with
a sequence of integers that mostly goes upward. The following function
could be used for that, if you set minStep
to a negative value:
void fillArrayRandomSequence( int arr[], int size, int minStep, int maxStep )
{
int j;
arr[0] = randInt( 0, maxStep );
for ( j=1; j<size; j++ )
arr[j] = arr[j-1] + randInt( minStep, maxStep );
}