-4

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.

Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77
User9123
  • 3
  • 2
  • You have to use `fib.Add` instead of indexer `fib[i]`, i.e., `fib.Add(fib[(i - 1)] + fib[(i - 2)])`. – dcg Nov 01 '17 at 13:41

1 Answers1

1

There is only 2 elements in your list, on i=2 iteration, it will throw an ArgumentOutOfRangeException exception.

SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • even when I do i= 3 it still doesn't work it should work though with i = 2 shouldn't it as 2-2 is 0 and the 0th element is the first element in the list? – User9123 Nov 01 '17 at 18:07