Ads block

Banner 728x90px

Fibonacci Series

We can write a program to display a fibonacci series by the use of recursive function easily.

Fibonacci series is a sequence of numbers in which the first two number are 1, and after that each number is the sum of previous two numbers.

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, .................


The problem of finding the nth Fibonacci number can be recursively defined as-

Basically the fibonacci series is based on two conditions that is given below:

  • If the value of n is equal to 0 or 1, function will return 1.
  • If the value of n is greater than 1, then the function will the sum of previous two numbers.
#include<stdio.h>
int fib(int n);
main()
{
    int nterms, i;
    printf("Enter number of terms: ");
    scanf("%d", &nterms);
    for(i=0; i<nterms; i++)
        printf("%d, ", fib(i));
    printf("\b");
}
int fib(int n)
{
    if(n==0 || n==1)
        return(1);
    return(fib(n-1) + fib(n-2));
}

This implementation of Fibonacci series is very inefficient because it performs same computations repeatedly.