To find Fibonacci series using c language | CTechnotips


Alogrithm:

What is Fibonacci series?

We assume first two Fibonacci are 0 and 1
A series of numbers in which each sequent number is sum of its two previous numbers is known as Fibonacci series and each numbers are called Fibonacci numbers. So Fibonacci numbers is

Algorithm for Fibonacci series
Fn = Fn-2 + Fn-1

Example of Fibonacci series:
0 , 1 ,1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55  ...

5 is Fibonacci number since sum of its two previous number i.e. 2 and 3 is 5
8 is Fibonacci number since sum of its two previous number i.e. 3 and 5 is 8 and so on

Code 1:

1. Write program to generate the Fibonacci series in c

#include<stdio.h>

void main(){

    int k,r;
    long int i=0l,j=1,f;

    printf("Enter the number range:");
    scanf("%d",&r);

    printf("FIBONACCI SERIES: ");
    printf("%ld %ld",i,j); //printing firts two values.

    for(k=2;k<r;k++){
         f=i+j;
         i=j;
         j=f;
         printf(" %ld",j);
    }

    getch();
}

Output:

Enter the number range: 15
FIBONACCI SERIES: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Code 2:

1. Fibonacci series using array in c

#include<stdio.h>

void main(){

    int i,range;
    long int arr[40];

    printf("Enter the number range: ");
    scanf("%d",&range);

    arr[0]=0;
    arr[1]=1;

    for(i=2;i<range;i++){
         arr[i] = arr[i-1] + arr[i-2];
    }

    printf("Fibonacci series is: ");

    for(i=0;i<range;i++)
    {
         printf("%ld ",arr[i]);
    }

    getch();
}

Output:

Enter the number range: 20
Fibonacci series is: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Code 3:

1. Fibonacci series in c using while loop

#include<stdio.h>

void main(){

    int k=2,r;
    long int i=0l,j=1,f;

    printf("Enter the number range:");
    scanf("%d",&r);

    printf("Fibonacci series is: %ld %ld",i,j);

    while(k<r){
         f=i+j;
         i=j;
         j=f;
         printf(" %ld",j);
         k++;
    }

    getch();
}

Output:

Enter the number range: 10
Fibonacci series is: 0 1 1 2 3 5 8 13 21 34

Code 4:

1. Sum of Fibonacci series in c

#include<stdio.h>

void main(){

    int k,r;
    long int i=0,j=1,f;
    long int sum = 1;

    printf("Enter the number range: ");
    scanf("%d",&r);

    for(k=2;k<r;k++){
         f=i+j;
         i=j;
         j=f;
         sum = sum + j;
    }

    printf("Sum of Fibonacci series is: %ld",sum);

    getch();
}

Output:

Enter the number range: 4
Sum of Fibonacci series is: 4

0 comments:

Post a Comment