FIBONACCI SERIES PROGRAM IN C



In this example , you will learn to print the Fibonacci series upto n terms (entered by user). 

The Fibonacci series is sequence in which next term is the sum of previous two terms. The first two terms of the Fibonacci series are 0 and 1.

The Fibonacci series of first 10 terms is :      
         
0     1      1       2      3     5    8     13    21      34

The next number is found by adding previous two numbers :

         > The third term , which is 1 , is the sum of first two terms 0 and 1.
         > Then 1 +1 =2 , and 2  is the fourth term i.e sum of 2nd and 3rd terms.
         > The 3 is found by adding two numbers before it (1+2).
         >  Then 5 is 2+3 .
         > and so on............


The Fibonacci series program can be written in C in two ways:
          1. Without recursion
          2. With recursion

Fibonacci series program in C without using recursion: 

//fibonacci series without recursion

#include<stdio.h> 
int main( )
{
int n1=0, n2=1, n3, i, number;
printf("Enter the number of elements:");                
scanf("%d",&number);

for(i=0;i <=number;++i)

{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}

return 0;


Fibonacci series program in C using recursion:

//fibonacci series program in C using recursion


#include
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("%d %d ",0,1);
printFibonacci(n-2);      //n-2 because 2 numbers( 0 and 1) are already printed

return 0;
}





Output: 

Enter the number of elements: 10
0  1  1   2   3   5   8   13  21  34



History of Fibonacci :
Fibonacci series was discovered by Leonardo Pisano Bogollo. "Fibonacci " was his name which means "son of Bonacci" . Being famous for  the Fibonacci series , he also helped spread of  Hindu-Arabic numericals (0,1,2,3,4,5,6,7,8,9)   in place of Roman numerals( I, II, III, IV, V  etc.)


Fibonacci Day:
November 23rd, is known as the Fibonacci Day. As it has  ' 1, 1,  2, 3' which is the part of the Fibonacci sequence. 
So, this November 23, let everyone know about it!




Just try this code by your own. If you have any doubts , then feel free to drop a comment . I'll be happy to answer questions in the comment section.
keep coding.






Comments

Post a Comment

Popular posts from this blog

DECIMAL TO OCTAL CONVERSION IN C

PROGRAM TO CONVERT BINARY CODE TO GRAY CODE

KRISHNMURTHY NUMBER PROGRAM IN C