random number in array

closed account (4ET0pfjN)
Hi, I want to write a function that takes the array size as parameter, and genereates random number as elems b/t 0 and twice the array size, but it's not working as the random values for each compiling is ALWAYS the same.

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
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int *createArray(int arraySize)
{
  int randElem;
  const int LOW = 0;
  const int HIGH = 2*arraySize;
	
  int *list = new int[arraySize];
	
  for ( int i = 0; i < arraySize; i++ )
  {
	srand(time(0));
	randElem = rand() % (HIGH - LOW + 1) + LOW;
	list[i] = randElem;
  }
	
  return list;
}

void printList(int *list, int numElem)
{ 
  for ( int k = 0; k < numElem; k++ )
  {
         cout <<list[k];
			
	 if ( k != numElem - 1 )//We don't need a comma for last item
		cout<<" , ";
  }
}

int main()
{
  int arraySize = 10;
  int *list_ = createArray(arraySize);
  printList(list_, arraySize);

  return 0;
}


Any help appreciated!
Last edited on
Call srand(time(0)) between lines 38 and 29. This seeds the random generator to the system time. Otherwise you'll see you get the results you describe, where it always starts of at the same point in the pseudo random sequence.
Last edited on
closed account (4ET0pfjN)
Thanks that worked by putting into main, but it also works if I remove from the for loop in function createArray but still place it ( srand(time(0)) ) within createArray.
You should only call srand once at the start of your program and never again to prevent fast code execution from giving you the same random numbers over and over. You must realize most simple programs like this take far less than a second to execute and time(0) only changes every second ;)
Last edited on
Topic archived. No new replies allowed.