C# & VS error: "make sure that the maximum index on a list is less than the list size"

I faced the error mentioned in the title when doing my homework, and simply can't find a way to remove it. Here is the method that I have this problem with:

public static double LaskeMiidi(double[] luvut)
{
    double ka = Keskiarvo(luvut);
    double miidi = luvut[0];

    for (int i = 0; i < luvut.Length; i++)
    {
        if (luvut[i] - ka < luvut[i + 1] - ka) // The line error points to!
        {
            miidi = luvut[i];
        }
        else
        {
            miidi = luvut[i + 1];
        }
    }
    return miidi;
}

So basically the problem is that when I say luvut[i + 1], at some point this index might become more than the length of the array is. I just can't figure out any ways to solve this problem, since I'm only a beginner with programming.

Jon Skeet
people
quotationmark

Yes, this is the problem:

for (int i = 0; i < luvut.Length; i++)
{
    if (luvut[i] - ka < luvut[i + 1] - ka)

When i is luvut.Length - 1, then i + 1 will be luvut.Length - and therefore an invalid index. (For an array of length x, the valid indexes are 0 to x - 1 inclusive.) You probably want to end one iteration earlier:

for (int i = 0; i < luvut.Length - 1; i++)

That way i + 1 will still be a valid index in the array - both in the if condition and in the body of the else clause.

people

See more on this question at Stackoverflow