0

I'm quite new at using arrays and functions in Visual Basic and I cannot seem to figure this out. My problem is that whenever I call the function Fibo it returns 0 no matter the value of n I give it. I'm sure the error is pretty basic.

Any pointer would be really appreciated!

Public Function fibo(n As Integer) As Integer

    Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci

    arrayFib(0) = 0 'idem
    arrayFib(1) = 1 'declare start value

    Dim i As Integer = 2 'start position

    While i <= n
        arrayFib(i) = arrayFib(i - 1) + arrayFib(i - 2)
        i = 1 + i

    Return arrayFib(i)
3
  • 3
    You missed End While. Just copy/paste mistake, or there is no End While in your code? Commented Sep 19, 2013 at 20:29
  • 1
    i becomes n + 1 and that value in the array is 0 (default value of INT). And also, should have End While (should even through an index out of bound exception). Commented Sep 19, 2013 at 20:29
  • @Cybȫʁgϟ37 It's an array of Integers, so there is no problem about the returning of a value (the type). Commented Sep 19, 2013 at 20:35

1 Answer 1

3
Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci

We can sort of guess where that +1 came from. You added it because your original code crashed with an IndexOutOfRangeException. Caused by you returning arrayFib(i), i was incremented to be larger than n, its value is n+1 after the loop. And thus returns the value of an element that was never assigned. You didn't fix it correctly :)

Fix the array declaration back the way it was and return arrayFib(n) instead.

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

1 Comment

If n is the number of Fibonacci digits to return, then the array declaration should be Dim arrayFib(n - 1) As Integer since in VB, the value specified when declaring an array is the upper bound, not the array size.

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.