Mar 11, 2020

C program 04


4.  C Program to find the nth number in Fibonacci series using recursion.
   
     Recursion is a programming technique In C, this takes the form of a function that calls itself.

    The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
     The next number is found by adding up the two numbers before it.
  • The 2 is found by adding the two numbers before it (1+1)
  • The 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and so on!
Example: the next number in the sequence above is 21+34 = 55

    #include <stdio.h>

    int fibo(int); /*Function Declaration*/

    int main()
    {
        int num;
        int result;
        printf("Enter the nth number in fibonacci series: ");
        scanf("%d", &num);
        if (num < 0)
        {
            printf("Fibonacci of negative number is not possible.\n");
        }
        else
        {
            result = fibo(num);
            printf("The %d number in fibonacci series is %d\n", num, result);
        }
        return 0;
    }
    int fibo(int num)
    {
        if (num == 0)
        {
            return 0;
        }
        else if (num == 1)
        {
            return 1;
        }
        else
        {
          return(fibo(num -1) + fibo(num - 2)); /*recursive function calling */
        }
    }


Output


 

No comments:

Post a Comment