• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Fibonacci's sequence using a recursive function

kaver

New Coder
Hello,

I was to write a program showing the value of an n element in the Fibonacci's sequence using a recursive function.

In Fibonacci's sequence, each number of the sequence is the sum of the two previous numbers. Thus, the sequence starts like this: 0, 1, 1, 2, 3, 5 ...

So far my code looks like this:

my code fibonacci:
#include <stdio.h>
#include <stdlib.h>

int        ft_fibonacci(int nb)
{
    if(nb < 0){
        return (-1);
    }

    if(nb == 0){
        return (0);
    }

    if(nb == 1){
        return (1);
    }
    return (ft_fibonacci(nb-1) + ft_fibonacci(nb-2));
}

int        main(void)
{
    printf("%d", ft_fibonacci(10));

    return (0);
}

However ! The number one being repeated 2 times and the second time it should repeat 2 instead of 1, the result is also (the element of the sequence - 1).

Can you please help me resolve this problem?

Many thanks in advance ! :))
 

Top