Saturday, February 16, 2013

C program to print first n fibonacci numbers

Fibonacci series is formed by adding two of its previous numbers .The first 2 fibonacci numbers are 0 and 1 . Series 0,1,1,2,3,5,8... is an example of fibonacci series .

Input   : 7
Output: 0 1 1 2 3 5 8

Code: (in C)
void print_fibonacci_numbers(int n)
{
if(n<0)
return;
if(n==1)
{
printf("0");
return;
}
if(n==2)
{
printf("0 1");
return;
}
int a=0,b=1,c,temp=n-2;
printf("0 1 ");
while(temp-- > 1)
{
c=a+b;
printf("%d ",c);
a=b;b=c;
}
}
view raw fibonacci.c hosted with ❤ by GitHub

Please let me know if you have any questions .

No comments: