A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 0,1, 1, 2, 3, 5, 8, etc.
- Using For Loop
- Through Function
- Through Recursive Function
- Using Pointer through Recursive Function
1. Using For Loop:
#include<stdio.h>
main() {
int i, first = 0, second = 1, sum, limit;
printf ("Enter The Limit: \n");
scanf ("%d", &limit);
printf ("%d %d\n",first, second);
for (i=1; i <= limit; i++)
{ sum = first + second;
printf ("%d \n",sum);
first = second;
second = sum;
} printf("\nThe %dth Fibonacci number is %d",limit, sum);
}
Output:
2. Through Function:
#include<stdio.h>
main() {
int n;
int fib;
int fibo (int n);
printf ("Enter the limit:");
scanf ("%d",&n);
fib = fibo(n);
printf ("\n The %dth Fibonacci number is %ld",n, fib);
} int fibo (int n)
{ int first, second, sum, i;
i = 1;
first = 0;
second = 1; printf ("%d \n%d",first,second);
while(i <= n) {
sum = first + second;
first = second;
second = sum;
i++;
printf ("\n%d",sum);
} return sum; }
Output:
3. Through Recursive Function:
#include<stdio.h>
main() {
int n,x,i;
int fib;
int fibo(int);
printf ("Enter the limit:");
scanf ("%d",&n);
n = n + 1;
for(i=0; i <= n;i++)
{ fib = fibo(i);
printf ("%d \n",fib); }
printf ("\n The %dth Fibonacci number is %ld",n-1, fib);
} int fibo(int x)
{ if (x==0)
return 0;
else if (x==1)
return 1;
else
return fibo(x-1) + fibo(x-2); }
Output:
4. Using Pointer through Recursive Function:
#include<stdio.h>
main() {
int fibo(int *a);
int fib,i,n;
printf ("Enetr th limit:");
scanf ("%d",&n);
n = n+ 1;
for(i=0; i <= n; i++)
{ fib = fibo(&i);
printf ("%d\n",fib);
} printf ("\nThe %dth Fibonacci number is %ld",n-1, fib);
} int fibo (int *b)
{ int n,f,s;
f = *b-1;
s = *b-2;
if(*b==0)
return 0;
else if (*b==1)
return 1;
else
return fibo(&f) + fibo(&s); }
Output:
C Program for Fibonacci Series
Reviewed by vijay pratap singh
on
May 10, 2017
Rating:
No comments: