Reputation: 1
I am writing a function to generate random numbers and then print them out in 10 rows and columns. The issue is that it just prints the same first 10 elements of the array containing the random numbers, over and over again. The first row should only have the first 10 elements, the second should have the elements between 10 and 20 and so on. I would appreciate if anyone sees what the issue is.
void numberGeneration(void){
#define COLUMN 10
#define ARRAYSIZE 900
#define ArrayMAX 900
#define ArrayMIN 100
srand( (int) time(NULL) );
int numArray[ARRAYSIZE];
/* Fill array with random numbers from ArrayMAX to ArrayMIN*/
for (int i = 0; i<ARRAYSIZE; i++) {
numArray[i] = rand() % (ArrayMAX + 1 - ArrayMIN) + ArrayMIN;
}
/* Print out 10 rows & 10 columns */
for (int k = 0; k < COLUMN; k++) {
for (int j = 0; j < COLUMN; j++) {
printf("%d ", numArray[j]);
}
/* Print the space*/
printf("\n");
}
}
I've tried altering the variable here:
for (int j = 0; j < COLUMN; j++)
to run all the way to the end of the array, but that just prints the entire array and gets rid of the rows.
I'm thinking you somehow need to use continue the loop after it has printed the first 10 elements, then keep going from 10 to 20, 20 to 30 and so on. Any help appreciated!!
Upvotes: 0
Views: 71
Reputation: 465
You need to index the array correctly inside the nested for loop (numArray[k * COLUMN + j]
instead of numArray[j]
) and for prettiness use \t
between numbers. See...
void numberGeneration(void){
srand( (int) time(NULL) );
int numArray[ARRAYSIZE];
/* Fill array with random numbers from ArrayMAX to ArrayMIN*/
for (int i = 0; i<ARRAYSIZE; i++) {
numArray[i] = rand() % (ArrayMAX + 1 - ArrayMIN) + ArrayMIN;
}
/* Print out 10 rows & 10 columns */
for (int k = 0; k < COLUMN; k++) {
for (int j = 0; j < COLUMN; j++)
printf("%d\t", numArray[k * COLUMN + j]);
/* Print the space*/
printf("\n");
}
}
Upvotes: 1