I am trying to create Fibonacci sequence for numbers less than 1 million and then find the sum of every even number in the sequence.
For this I am trying to create a list with the Fibonacci sequence and then use a for loop with mod to find even numbers (n % 2 = 0) and then add them but when attempting to create a Fibonacci sequence I encounter this error:
System.ArgumentOutOfRangeException.
Here is my Code:
{
class Program
{
static void Main(string[] args)
{
// creates a list with the fib[0]= 0 and fib[1] = 1
List<int> fib = new List<int>(new int [] {0, 1});
/// for loop that creates the next element in the fib sequence list by creating the next element by adding the previous two elements.
for (int i = 2; i < 100; i++)
{
fib[i] = (fib[(i - 1)] + fib[(i - 2)]);
}
Console.WriteLine(fib);
Console.ReadLine();
}
}
}
This comes up with no build errors so I can't solve the problem. I thought that the i - 2 might result in a negative number which is what the problem is and is what c# suggests but I don't think that is the case.