facebook like button

01 May, 2011

program 38: Fibonacci series

The need:
     This is a simple program to print Fibonacci series upto certain number of terms. This program was given to me a assingment in lab.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i=0,j=1,k=1,m=1,n;
    printf("Enter the number of terms.");
    scanf("%d",&n);
    printf("\nterm no. \tvalue\n");
    printf("%d\t\t%d\n",m,k);
        for(m=1;m<n;)
        {
            k=i+j;
            printf("%d\t\t%d\n",++m,k);
            i=j;
            j=k;
        }
    printf("\n\n");
}
-------------------------------------------- 

The approach: 
This program creates a Fibonacci series upto the terms given by the user. The logic is simple. Just go with the definition of Fibonacci that any term is the sum of its two preceding terms. Here k always hold current term and i and j hold previous 2 terms(except for first 2 terms case).

Remarks:
1. In this program if you enter a large number of terms, the program fails to give correct output after certain number of terms. This is because of size limit on integers in C. 
 

3 comments:

  1. Hi ,
    I am trying to print the fibonacci series using recursion but somewhere I have made a mistake but I can spot it.Please help me fix it.
    This is my code :

    #include
    int fibonacci(int);
    int main()
    {
    int n,i,m=0; /*m is the first term of series */
    printf("enter the number of terms in series \n");
    scanf("%d",&n);
    for(i=1;i<=n;i++);
    {
    printf("%d \n",fibonacci(m));
    m++;
    }
    return 0;
    }
    int fibonacci(int n)
    {
    if(n==0)
    return 0;
    else if(n==1)
    return 1;
    else
    return ( fibonacci(n-1)+ fibonacci(n-2));
    }

    ReplyDelete
    Replies
    1. Anyways remove the ;(semicolon) at the end of line containing for loop. Rest all is fine.

      Delete

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply