CuriousLekgolo CuriousLekgolo - 18 days ago 7
C# Question

Calculating Averages Throws an "System.IndexOutOfRangeException" Exception

I'm trying to write a gold prospecting program that takes an initial data map in the form of a 2D array which then produces a map with all the likely places for gold marked on it.

However, when calculating the average to determine whether or not to mark the point for prospecting, I get a "System.IndexOutOfRangeException" exception thrown at me and the program breaks. How would I go about fixing this? Thank you for any help in advance.

for (int i = 1; i < nRows; i++)
{
for (int j = 1; j < nCols - 1; j++)
{
//it is at the line below where the program breaks
double average = (data[i - 1, j] + data[i + 1, j] + data[i, j - 1] + data[i, j + 1]) / 4;


if (data[i, j] > average)
{
map[i, j] = "*";
}
}
}

Answer

You go out of borders of your 2-D array. So change this part of your code:

for (int i = 1; i < nRows; i++)
    {
        for (int j = 1; j < nCols - 1; j++)

to

for (int i = 1; i < nRows - 2; i++)                  // NOT from 0 to nRows - 1
    {
        for (int j = 1; j < nCols - 2; j++)          // NOT from 0 to nCols - 1

so you omit the borders.

Comments