mercredi 17 février 2016

Create randomly sized (within a certain range) arrays over many iterations

I am trying to create many arrays consisting of random numbers and of random size between the range of, say, 1 and 20 elements. My code works SOMETIMES.

I am using a random number between my desired range to determine the array size. If the first iteration produces an array size of value 10, say, then for some reason my code does not want to create any arrays of size larger than 10. Various arrays will be created (and the list of those arrays will be outputed) until a certain iteration produces a random number larger than 10. Then I get this error:

Array index out of range numbers->[11] valid upto numbers[9]

"numbers" is the name of the array. Here is the relevant portion of my code:

{

int j, flag = 0;
int temp;
int rand=1;


for(int t=0; t<50; t++)         {

int length = rand()% 20 + 1;
cout<<"length is " << length << endl;
int numbers[length];

for(int i = 0; i < length; i++){
numbers[i]=rand();
cout << numbers[i] << endl;
                }

for(j=0; (j<=length); j++)      

{
for (int i=0; i<(length-1); i++)
{
    if(numbers[i+1]<numbers[i])
    {
        temp=numbers[i];
        numbers[i]=numbers[i+1];
        numbers[i+1]=temp;
        flag++; 
    }
 }
}   

cout << "Number of Swaps : " << flag << endl; 

                 }

}




Aucun commentaire:

Enregistrer un commentaire