0

I'm trying to write a C program that outputs the fibonacci numbers using an iterative function. I want to use an array which containing the Fibonacci numbers The program gives me the wrong fibonacci values, I cannot see any mistake

Please help here is my programm:

    #include <stdio.h>
    
    int fibonacciL(int unsigned value){
    int i;
    const int MAX = value;
    int fibo[MAX];
    
    fibo[0]=0;
    fibo[1]=1;
    
        for(i=2;i<value+1;i++)
        {
        fibo[i]= fibo[i-1] + fibo[i-2];
        return fibo[value];
        }
    }
    
    int main(){
    int value;
    printf("Iterativ Fibonacci\n");
    printf("Enter a Number:");
    scanf("%d", &value);
    printf("For the number %d the value is: %d\n",value,fibonacciL(value));
    return 0;
}

1 Answer 1

1
  • You allocated the array fibo one element less than required.
  • You returned fibo[value] before calculating that.
int fibonacciL(int unsigned value){
    int i;
    const int MAX = value;
    int fibo[MAX+1]; /* allocate one more element so that fibo[value] become available */
    
    fibo[0]=0;
    fibo[1]=1;
    
    for(i=2;i<value+1;i++)
    {
        fibo[i]= fibo[i-1] + fibo[i-2];
    }
    return fibo[value]; /* move this to right place */
}
Sign up to request clarification or add additional context in comments.

1 Comment

ouuu i overlooked that, sorry and Thank you for the quick response

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.