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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

#include <iostream>
#include <iomanip>

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...

1
2
3
4
5
6
7
8
	
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):
1
2
3
4
5
6
7
#include <time.h>

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:

1
2
3
4
//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.