Thursday 5 June 2014

0

C Program 16: To Print The Fibonacci Series Using Recursion

  • Thursday 5 June 2014
  • IndianBooktuber
  • Share
  • Aim: To print fibonacci series
    Fibonacci series is the one in which every third number is the sum of first two.
    The series is 1,1,3,4,7,11,18....
    //To print the fibonacci series using recursion
    #include<stdio.h>
    #include<conio.h>
    int fibo(int x);
    void main()
    {
         int a=1, b=1, n,p;
         printf("Enter the number of digits you want to print: ");
         scanf("%d", &n);
         printf("The fibonacci series is:\n%d\n%d", 1 , 1);
         fibo(n);
         getch();
    }
    int fibo(int x)
    {
        static int a =1 , b=1, temp, c;
        if (x-2==0)
        {
                   return 0;
        }
        else
        {
            c=a+b;
            printf("\n%d", c);
            temp=b;
            b=c;
            a=temp;
            fibo(x-1); //using recursion
        }
    }

    The code is fairly simple. We have printed the first two number using a simple printf statement in the main function. Then we have called the fibo()
    Now, say we want to print the first 25 numbers in the series. that would mean value of n is 25. But we have already printed first two numbers in main function. So, in the fibo(), in if statement, we would put a condition for x-2 numbers i.e. 23 numbers.
    Now, we would use simple arithmetic operation c=a+b; 
    This would give us the third number. Then we have performed swapping of the numbers. And then we have called the same fibo() function. 

    0 Responses to “C Program 16: To Print The Fibonacci Series Using Recursion”

    Post a Comment

    Subscribe