Tuesday, November 15, 2011

Find fibonacci number at position n: recursion

#include <stdio.h>

int fib(int n)
{
    if(n<=1)
        return n;
    return fib(n-1)+fib(n-2);
}


int main()
{
    int a,r;
    printf("Enter any number : ");
    scanf("%d",&a);
    r=fib(a-1);
    printf("The no. at position %d is %d\n",a,r);
    return 0;
}


Print fibonacci series upto n: Without recursion

#include <stdio.h>

int main()
{
    int first=0,second=1,next,i,n;
    printf("Enter the limit: ");
    scanf("%d",&n);
    for(i=0; i<=n-1; i++)
    {
        if(i<=1)
            next = i;
        else
        {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d ",next);
    }
}

Print fibonacci series upto n: recursion

/* Print fibonacci series upto n: recursion */
#include <stdio.h>

int fib(int n)
{
    if(n <= 1)
        return n;
    else
    {
        return fib(n-1) + fib(n-2);
    }
}

int main()
{
    int n,i;
    printf("Enter the limit: ");
    scanf("%d",&n);
    for(i=0; i
    {
        printf("%d ",fib(i));
    }
    return 0;
}