You are using a version without Ads of this website. Please, consider donating:

### Matrix with srand

What up Gents?
I have this code here and I wanted to use srand() to fill it instead of my own literals. Where would I put and how would I use the srand()? And no this is not homework. I am on a break from school and could never figure it out for a problem I had in a C++ 2 class. Thanks for the help.
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445`` `````` #include #include using namespace std; const int NUMBER_OF_ROWS = 6; const int NUMBER_OF_COLUMS = 5; void printMatrix( int matrix[][NUMBER_OF_COLUMS], int NUMBER_OF_ROWS ); int main() { int board [NUMBER_OF_ROWS][NUMBER_OF_COLUMS] = { { 23, 5, 6, 15, 18 }, { 4, 16, 24, 67, 10 }, { 12, 54, 23, 76, 11 }, { 1, 12, 34, 22, 8 }, { 81, 54, 32, 67, 33 }, { 12, 34, 76, 78, 9 } }; printMatrix ( board, NUMBER_OF_ROWS ); cout << endl; cin.get(); return 0; } void printMatrix ( int matrix[][NUMBER_OF_COLUMS], int noOfRows) { int row,col; for( row = 0; row < noOfRows; row++ ) { for( col = 0; col < NUMBER_OF_COLUMS; col++) cout << setw(5) << matrix[row][col] << " "; cout << endl; } } ``````
u would put it in a double for loops...

 ``12345678`` `````` for( row = 0; row < noOfRows; row++ ) { for( col = 0; col < NUMBER_OF_COLUMS; col++) matrix[row][col] = myRandomInt cout << endl; }``````

call srand in the top of main class

and use rand to generate the number...
To add to what oonej said, srand() is used to seed the rand() function (To make sure it always generates different values) Most people call this at the beginning of main, using the help of time(NULL):
 ``1234567`` ``````#include int main() { srand(time(NULL)); //time(NULL) will always be different for every instance of the program return 0; }``````

Then, use the rand() function to generate a random value. To get a specific range of values, use the modulo (%) operator:

 ``1234`` ``````//After seeding srand() int MyRand = rand(); int MyRand2 = rand()%100 //MyRand2 is between 0 and 99 int MyRand3 = rand()%100+1 // MyRand3 is between 1 and 100 ``````
Topic archived. No new replies allowed.