algorithms

Fibonacci Versions – C

This post covers the three implementation(Iterative, Recursive and Dynamic) version of Fibonacci series. The correctness of the code covers for integer range numbers only.

1. Iterative Version


#include 

int fibo(int n)
{
    int previous = 1;
    int current = 1;
    int next = 1;
    int i;
    for (i = 3; i <= n; i++)
    {
        next = current + previous;
        previous = current;
        current = next;
    }
    return next;
}

int main()
{
    int n;
    int result;
    printf("Enter the required nth number in fibonacci series: ");
    scanf("%d", &n);

    if (n == 0)
        result = 0;
    else
        result = fibo(n);
    printf("The %d number in fibonacci series is %d\n", n, result);

    return 0;
}

 

2. Recursive Version


#include 

int fibo(int n)
{
    if (n == 0)
        return 0;
    else if (n == 1)
        return 1;
    else
        return(fibo(n - 1) + fibo(n - 2));
}

int main()
{
    int n;
    int result;
    printf("Enter the required nth number in fibonacci series: ");
    scanf("%d", &n);

    result = fibo(n);
    printf("The %d number in fibonacci series is %d\n", n, result);

    return 0;
}

 

3. Dynamic Programming Version


#include 

int fibo(int n)
{
    int fib[n+1];
    int i;
    fib[0] = 0;
    fib[1] = 1;

    for (i = 2; i < n + 1; i++)
        fib[i] = fib[i - 1] + fib[i - 2];

    return fib[n];
}

int main()
{
    int n;
    int result;
    printf("Enter the required nth number in fibonacci series: ");
    scanf("%d", &n);

    if (n == 0)
        result = 0;
    else
        result = fibo(n);
    printf("The %d number in fibonacci series is %d\n", n, result);

    return 0;
}

One thought on “Fibonacci Versions – C

Let me Know What you Think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s