1

So I have an Array with 100 int elements, that have to be drawn randomly within the range [-100,100], and has to return the amount of numbers that are odd and are within this range [-30,30]. And I do this:

int counter = 0;
int i = 0;
int[] numbers = new int[100];
for ( i = 0; i <= numbers.Length; i++)
{
    Random rnd = new Random();
    numbers[i] = rnd.Next(-100, 101);
    if (numbers[i] % 2 != 0)
    {
        if (numbers[i] >= -30 && numbers[i] <= 30)
        {
            counter++;
        }
    }
}
Console.WriteLine(counter);

And I build and receive no errors. But when running I receive this error on the command prompt: System.IndexOutOfRangeException: Index was outside the bounds of the array. Then it guides me to this line:

numbers[i]=rnd.Next(-100,101);

So, like, what's happening? What is the wrong thing I did?

  • 2
    change your for condition from i <= numbers.Length to i < numbers.Length. Remember that your array index are from 0 to length -1 – Conrado Costa Nov 06 '15 at 12:55
  • 4
    You'll also want to move the `Random rnd = new Random();` outside of the loop to prevent getting the same value on more than one iteration as per [this answer](http://stackoverflow.com/questions/26005230/method-displays-incorrect-results/26005673#26005673). – petelids Nov 06 '15 at 12:58

2 Answers2

5

Replace <= with < in the for-loop. So

for ( i = 0; i < numbers.Length; i++)

instead of

for ( i = 0; i <= numbers.Length; i++)

collections are zero based in .NET. So you find the first item at 0 and the last at index 99.


You should also move the Random initialization outside of the loop:

Random rnd = new Random();
for ( i = 0; i < numbers.Length; i++)
{
    // Random rnd = new Random();  <--- No, no!

Because the default constructor uses the current time as seed for the Random. When you use the same seed you will always generate the same sequence. Since the loop is executed too fast the same seed is used.

Quote:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

your array is iterating from 0 to 100

use:

for ( i = 0; i < numbers.Length; i++)
amit dayama
  • 3,246
  • 2
  • 17
  • 28