Fibonacci series in C programming
Fibonacci
series in c programming using loops and recursion. You can print as many terms
of series as your required. The number of the sequence is known as Fibonacci numbers
in c programming. The series start as 0,1,1,2,3,5,8….,. Except for the first
two terms of the sequence every other terms is sum of previous two terms for
example 5=3+2(addition of 3 and 2).
Fibonacci series Program example in C
#include <stdio.h>
int main()
{
int n, first = 0, second = 1, next, a;
printf("Enter the number of terms\n");
scanf("%d", &n);
printf("First %d terms of Fibonacci series are:\n", n);
for (a = 0; a < n; a++)
{
if (a <= 1)
next = a;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n", next);
}
return 0;
}
Fibonacci series Program example in C |
Fibonacci series C programming program using recursion
#include<stdio.h>
int f(int);
int main()
{
int n, i = 0, a;
scanf("%d", &n);
printf("Fibonacci series terms are:\n");
for (a = 1; a <= n; a++)
{
printf("%d\n", f(i));
i++;
}
return 0;
}
int f(int n)
{
if (n == 0 || n == 1)
return n;
else
return (f(n-1) + f(n-2));
}
Fibonacci series C programming program using recursion |
The recursive method is less efficient as it involves
reoeated function call while calculating larger term of the series it may lead
to stack overflow. We can reduce the running time of the recursive algorithm by
using memorization( storing Fibonacci numbers that are calculated in an array
and using array for lookup). The Fibonacci series has many application in mathematics
and Computer and software engineering.
Post a Comment