I'm creating a method which finds smallest absolute difference between next and previous elements value.
It occurs that ArgumentOutofRange exception in method. But however when i add try, catch exception it works. What was the problem in my code? however i created proper conditions like "if i equals 0" of course it can't find [i-1], then its will be difference between next value[1] and [0]. And if its became last element then value will be difference between its(last[i-1]) and previous ([i-2])
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
List<Cla> Clalist = new List<Cla>();
Clalist.Add(new Cla(0));
Clalist.Add(new Cla(2));
Clalist.Add(new Cla(3));
Clalist.Add(new Cla(10));
Clalist.Add(new Cla(100));
Clalist.Add(new Cla(65));
Program nn = new Program();
nn.GetAbs(Clalist);
Console.WriteLine(Clalist[0].AbsValue);
Console.WriteLine(Clalist[1].AbsValue);
Console.WriteLine(Clalist[2].AbsValue);
Console.WriteLine(Clalist[3].AbsValue);
Console.WriteLine(Clalist[4].AbsValue);
Console.WriteLine(Clalist[5].AbsValue);
Console.ReadLine();
}
public void GetAbs(List<Cla> n)
{
int z = n.Count;
for (int i = 0; i < z; i++)
{
if(i == 0)
{
n[0].AbsValue = Math.Abs(n[1].Value - n[0].Value);
}
if(i == (z-1))
{
n[z-1].AbsValue = Math.Abs(n[z-1].Value - n[z -2].Value);
}
else
{
try
{
var AbsV = Math.Abs(n[i + 1].Value - n[i].Value);
var AbsV2 = Math.Abs(n[i - 1].Value - n[i].Value); //exception occurs here
if (AbsV < AbsV2)
n[i].AbsValue = AbsV;
else
n[i].AbsValue = AbsV2;
}
/* catch (ArgumentOutOfRangeException)
{
n[0].AbsValue = n[1].Value - n[0].Value; */ When i add this it works
}
}
}
}
}
}
class Cla
{
public int Value;
public int AbsValue;
public Cla(int v)
{
Value = v;
}
}