I have created an Array of 36 random numbers between 1-49. I have nested a do-while loop inside of the for loop that inserts the numbers into the array to remove any duplicate numbers. When running the code to test I get an exception "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"
{
Random rand = new Random();
int[] Numbers = new int[36];
for (int r = 0; r <= 36; r )
{
int nextValue;
do
{
nextValue = rand.Next(1, 50);
} while (Numbers.Contains(nextValue));
Numbers[r] = nextValue;
}
return Numbers;
}
Numbers[r] = nextValue; caused the exception.
Does anyone know where I'm going wrong?
CodePudding user response:
You initialise your numbers array with 36 spaces
Numbers = new int[36];
But inside your loop, you assign to number is place up to 49
for (int r = 0; r <= 49; r )
.....
Numbers[r] = nextValue;
Your loop max value should be changed to 36, it is not related to the maximum value you require from the Random generation