if (theArray[i-1] < theArray.Length && theArray[i-1] != null)
Is what i got after some research. But it gives just gives me out of index error, because i do i-1.
But i want the if statement to check whether the key/index on i-1 exists, then do something..
See what i want to do is plus the values of the indexes next to the current index.
for (int i = 0; i < theArray.Length; i++)
{
Left = 0;
Right = 0;
if (i != 0)
{
Left = theArray[i - 1];
}
if (theArray[i + 1] < theArray.Length)
{
Right = theArray[i + 1];
}
calc = Left + Right;
output2.Text += calc + ", ";
}
So if the left is there then change the left value (default is 0, right and left), and if right is there then change the right value. And then calculate both values taken from theArray[].
E.g if its on theArray[16] it should take the left, theArray[15] and theArray[17] and plus together.
I think you are looking for:
Or possibly:
I would normally be using
iin a loop like this:Update:
You can’t use
i-1, because on the first iteration, wheni == 0, this would evaluate to-1. This is an illegal index in an array.Update 2:
I think I understand what you are trying to do now. Here is one way to do it: