Index outside the limits of the matrix - C #

0

I have a problem with my code, I'm trying to make comparison of numbers within an array, only that it gives me an index error outside the limits of the array. I hope you can help me, I would thank you very much, I leave my code

if ((array[0]) > (array[1]))
{
    poss = true;
}
else
{
    poss = false;
}
for (int i = 1; i < array.Length; i++)
{
    if ((array[i]) < (array[i + 1])  && poss == true)
    {
        h++;
        poss = false;
    }
    if ((array[i]) > (array[i + 1]) && poss == false)
    {
        h++;
        poss = true;
    }
}

eh = ((n * 2) - 1) / 3;
vh = ((n * 16) - 29) / 90;
zcal = (h - eh) / Math.Sqrt(vh);
MessageBox.Show(zcal.ToString());

My error occurs when it reaches the next line of code:

if ((array[i]) < (array[i + 1])  && poss == true)

My Array is 20 numbers

    
asked by elias459 06.11.2018 в 04:50
source

1 answer

1

Good as the solution has been commented is the following:

replace

for (int i = 1; i < array.Length; i++)

for

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

But it seemed right to explain why, mainly for future visitors.

Well the error occurred in your case to have an array of 20 numbers for example.

Calling the length property of the array returns the amount of data it contains, in this case 20 examples are included.

If we remember the arrays they contain multiple data that are stored in a different direction within them ie in a specific position and we refer to that position by means of an index that is expressed in numbers and there is the point in how they are expressed the positions of the array.

Since the Length property returns the amount of data we might think we can cycle with that value to traverse the array. For example:

for (int i = 1; i < array.Length; i++)

But as we saw in this question that will not work. Already:

In the example we have an array of 20 data.

But there is no data position 20, but why?

Because the positions of data in the array as everything in programming start with 0 . Exactly the first data of our array will be stored in the position 0 . So if we have 20 data and data positions start from 0 we have from 0 to 19 with data (if we count from 0 to 19 we have a total of 20 numbers).

Knowing this our cycle for we should start the cycle in 0 to be able to use the cycle variable to access the data:

for (int i = 0; i < array.Length; i++)

var obtenerDatos = array[i];

And that way we get all the data from an array.

You can also avoid confusion, we can use a special cycle that is the foreach .

    
answered by 06.11.2018 / 23:33
source