Creating Random elements in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shellina Reeves
    New Member
    • Jun 2011
    • 1

    Creating Random elements in an array

    Basically I need to create array eleements for an array using rand (). However whenever the code that I provide, the array is filled with the same random array. I am thinking that I need to do somehting with the count++ to get it to repeat. Can someone please help me out?

    Code:
     void RandArray (int mainArray[], int count)
     {/*RandArray */
    	int minRange;	// the minimum value the user decides for the array
    	int	maxRange;	// the maximum values the suer decided for the array
    	int randNum;	// the random number generated 
    
    
    	// User sets MAX and MIN array values
    	cout << "Minimum Value for the Array values: " ;
    	cin >>  minRange;
    	cout << "Maximum Value for the Array values: " ;
    	cin >> maxRange;
    	
    	randNum = (minRange + rand() % maxRange);
    
    	// main loop to iterate numbers
    	for (count = 0; count < ARRAY_SIZE; count++)
    	{
    		mainArray[count] =randNum;
    	
    	}
    
    
    	
     }/* RandArray
    For example if I set minRange = 10 and MaxRange = 40
    the mainArray becomes {11,11,11,11,11 ,11,11,11,11,11 ,11,11,11,11,11 }

    Help please!
    Shellina
    Last edited by Niheel; Jul 17 '11, 04:55 PM. Reason: code tags
  • Ramsin
    New Member
    • Jul 2011
    • 15

    #2
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    using namespace std;
    
    int main() {
    	srand(time(NULL));
    	int n = rand()%10 + 1;
    	int a[n];
    	
    	for(int i=0; i < 10; i++) {
    		a[i] = rand()%100 + 1;
    		cout << a[i] << endl;
    		i++;
    	}
    }

    Comment

    • Ramsin
      New Member
      • Jul 2011
      • 15

      #3
      Read about srand: http://www.cplusplus.com/reference/c...cstdlib/srand/

      Comment

      Working...