2 Aug 2019

  • August 02, 2019
  • Amitraj







Fibonacci Series in C

Fibonacci Series in C:  In case of fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0 and 1.


There are two ways to write the fibonacci series program:

1.Fibonacci Series without recursion
2.Fibonacci Series using recursion

/* C Program to print Fibonacci series up to n(without Recursion) */

#include<stdio.h>

int main()

{
int n,f1=0,f2=1,f3,i;
printf("Enter a no:");   

printf("0\t1\t");
for(i=0;i<n-2;i++)
{

f3=f1+f2;
printf("%d\t",f3);
f1=f2;
f2=f3;
}
return 0;
}


INPUT/OUTPUT:
Enter a no:8
0 1 1 2 3 5 8 13



/* C Program to print Fibonacci series up to n(using Recursion)  */ 


#include<stdio.h>    
void printFibonacci(int n)
{    
    static int n1=0,n2=1,n3;    
    if(n>0) 
{    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         printf("%d ",n3);    
         printFibonacci(n-1);    
    }    
}    
int main()
{    
    int n;    
    printf("Enter the number of elements: ");    
    scanf("%d",&n);    
    printf("Fibonacci Series: ");    
    printf("%d %d ",0,1);    
    printFibonacci(n-2);  //n-2 because 2 numbers are already printed    
     return 0;  
 }    


INPUT/OUTPUT:
Enter the number of elements: 12

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89

http://codevidyalay.blogspot.com








Translate

Popular Posts