Reputation: 3
I have a project due for my C class tomorrow and part of it is creating a user defined matrix. The user will enter how many rows and how many columns the matrix has, as well as what numbers are minimum and maximum within the matrix. The numbers are random between the user defined numbers. After everything is input, the matrix is supposed to be displayed.
It compiles and runs, but doesn't do anything except display one random number.
This is what I have so far:
float GetUserInfo(){ //getting the user to define the size and values of the matrix
int nrows, ncol, min, max;
int matrix[50][50],i, j;
printf("Please enter the number of rows and columns for the matrix:\n");
printf("number of rows: ");
scanf("%d", &nrows);
printf("number of columns: ");
scanf("%d", &ncol);
printf("Now enter the min and max value:\n");
printf("min value: ");
scanf("%d", &min);
printf("max value: ");
scanf("%d", &max);
for(i=0;i<nrows;i++){
for(j=0;j<ncol;j++){
}
}
matrix[i][j]=rand();
printf("The matrix generated is:\n%d \t", matrix[i][j]);
return;
}
Upvotes: 0
Views: 1251
Reputation: 49523
Before you use rand()
you need to seed it with srand()
to get a random numbers or else you'll keep getting the same number over and over again:
srand((int)time(NULL));
Second.. unless you copied your code incorrectly, you're placing the number outside the loop:
for(i=0;i<nrows;i++){
for(j=0;j<ncol;j++){
//<--| You wanted that matrix population placed in the loop
} // |
} // |
// |
matrix[i][j]=rand(); // ---
printf("The matrix generated is:\n%d \t", matrix[i][j]); // move this line too
Another point, since you ask for number or rows and cols here:
printf("number of rows: ");
scanf("%d", &nrows);
printf("number of columns: ");
scanf("%d", &ncol);
But you hardcoded the array size to 50x50, you should validate that the nrows
and ncol
entered is within the bounds of your array or you'll start trying to access memory you don't own.
Final point, you ask for max and min values to place in there, but you're not putting any boundaries on the rand()
function. There are lots of examples on how to do this.
Upvotes: 0
Reputation: 974
These lines
matrix[i][j]=rand();
printf("The matrix generated is:\n%d \t", matrix[i][j]);
are outside the for loops therefore you are getting only one random value displayed. Put this line inside the nested for loops
matrix[i][j]=rand();
and set the limit on rand() function to generate a number between max and min. See rand() for details.
Upvotes: 0
Reputation: 8839
You are not assigning any value inside the loop. Move matrix[i][j]=rand();
to within the loop.
Also, you need to use a nested loop to print the matrix values.
To generate the random number in specified range, you should use matrix[i][j] = min + rand() * (max-min) / RAND_MAX;
Upvotes: 1