Friday, October 30, 2009

Fibonacci Sequence

Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89...

void main()
{ void Fib(float,float,float);
float e,d;
/* i put d=24 because the function will start off by printing 1 and starts counting its recursion only after the first digit so if i want 25 numbers its 25-1=24*/
d=24;
e=1;
printf("\Display Fibonacci sequence");
Fib(d,e,1.0);
}



void Fib(float x,float a,float b)
{
if(a==1)

printf("\n1");

if(x==0)
exit();
printf("\n%f",a);
if(x==1)
exit();
b=a+b;
printf("\n%f",b);
Fib(x-2,a+b,b);
}

6 comments:

  1. Code is wrong
    not compiling at all......

    ReplyDelete
  2. #include
    int first=1,second=1,next;
    main()
    {
    int n;
    printf("Enter a number of term of fibonacci series :");
    scanf("%d",&n);
    n = n-2;
    printf("1,1,");
    fibo(n);
    printf("\n");
    }
    fibo(int m)
    {
    next = first+second;
    first = second;
    second = next;
    printf ("%d,",next);
    m--;
    if (m==0)
    {return 0;
    }
    else
    {
    fibo (m);
    }
    }

    ReplyDelete
  3. #include
    #include
    int fibonacci(int x);
    void main()
    {
    int s;

    printf("Enter the number for fibonacci series\n");

    scanf("%d",&s);
    printf("The fiboacci series for the sequence %d are\n ",s);
    fibonacci(s);
    }

    int fibonacci(int x)
    { static int f1=0,f2=1;
    int f;

    if(x==1)
    {
    f=f1+f2;
    printf("%d ",f);
    }
    else
    {
    f=f1+f2;
    f2=f1;
    f1=f;
    printf("%d ",f);
    fibonacci(x-1);
    }
    }

    ReplyDelete
  4. #include
    void sequence(int,int,int);

    void main()
    {
    int a=1,b=1,c=1;

    sequence(a,b,c);

    }


    void sequence(int x,int y,int z)
    {

    if(x==1)
    {
    printf("%d\n",x);
    printf("%d\n",x);
    }

    if(z<=23)
    {
    printf("%d\n",x+y);
    sequence(x+y,x,z+1);
    }

    }

    ReplyDelete
  5. main()
    {

    int a=0, b=1,c,d,e=20;

    fibbo(a,b,c,e);
    }
    void fibbo(int p, int q, int r,int s)
    {
    if(s==0)
    {
    exit(0);
    }
    else
    {
    r=q;
    printf(" %d",q);
    fibbo(p=r,q=q+p,r,s=s-1);
    }

    }




    ReplyDelete
    Replies
    1. main()
      {

      int a=0, b=1,c,d;

      fibbo(a,b,c);
      }
      void fibbo(int p, int q, int r)
      {static int s=25;
      if(s==0)
      {
      exit(0);
      }
      else
      {
      r=q;
      s=s-1;
      printf(" %d",q);

      fibbo(p=r,q=q+p,r);
      }

      }

      Delete