1

Going to offer myself for the slaughter here.

Have checked the other questions avail, and can't seem to find the cause of my IndexOutOfRange exception for the following code:

public static int fib2(int n)
    {
        int[] fibarray = new int[n];

        if (n == 0) return 0;

            fibarray[0] = 0;
            fibarray[1] = 1;

            for (int i = 2; i < n; i++)
            {
                fibarray[i] = fibarray[i - 1] + fibarray[i - 2];

            }

            return fibarray[n];

     }

It's something really stupid I'm sure but it's driving me loopy (pun intended)...

1
  • tracing this in debug would tell you exactly what the problem is, try with n = 1 Commented Jun 11, 2012 at 12:35

1 Answer 1

4

That's the last line!

return fibarray[n];

Your last index in your table is n-1, not n.

Update

And like Attila said, if n=1, the line

fibarray[1] = 1;

will also make a IndexOutOfRange

Sign up to request clarification or add additional context in comments.

2 Comments

Also, fibarray[1] = 1; is only valid if n>=2
Yep indeed, i'll add this. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.