Thursday, 25 September 2014

C Program for generating Fibonacci Series

Fibonacci series is a series of integer numbers where the first two numbers in the series are 1 and 1, or 0 and 1, depending on the chosen starting point of the series, and each subsequent number is the sum of the previous two numbers  ie. Fn = Fn-1  +  Fn-2.


For example:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ….

Or

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

Source Code

fibo.c


#include<stdio.h>

int main() {
    int n, first = 0, second = 1, next, i;

    clrscr();
    printf("Enter the number of terms you want:");
    scanf("%d",&n);

    printf("\n\nFibonacci Series\n\n");
    for ( i = 0 ; i < n ; i++ ) {
        if ( i <= 1 )
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d, ",next);
    }

    printf("\n\nPress any key to continue...");
    getch();

    return 0;
}




Output

Enter the number of terms you want:15

Fibonacci Series
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,

Press any key to continue...


No comments:

Post a Comment