The Fibonacci sequence is a series of numbers where the next number is the addition of the last two numbers, the Fibonacci series starts with 0, and 1.
For example, if we want to find Fibonacci of the 5th term then using recursion we will get the following.
fib(5) = fib(4) + fib(3)
fib(4) = fib(3) + fib(2)
fib(3) = fib(2) + fib(1)
fib(2)=fib(1)+fib(0)
fib(1)=1
fib(0)=0
#include<stdio.h>
int fibs(int a)
{
if (a==0)
return 0;
else if(a==1)
return 1;
else
return (fibs(a-1)+fibs(a-2));
}
int main()
{
int a,i,fib;
printf("\n enter the fibonacci length:");
scanf("%d",&a);
printf("fibonacci series are:");
for(i=0;i<a;i++)
{
fib=fibs(i);
printf("%d\t",fib);
}
return 0;
}
enter the fibonacci length:7 fibonacci series are:0 1 1 2 3 5 8
fibs
function i.e Fibonacci series function. it will calculate the Fibonacci series value.main()
.a
. fibs
function from 0 to till a
value.
for(i=0;i<a;i++)
{
fib=fibs(i);
printf("%d\t",fib);
}
i
value is 0 it will call fibs(0)
function, and fibs(0)
function will return a value 0. because inside our fibs function we have written
if (a==0)
return 0;
i
value is 1 it will call fibs(1), the function will return value 1.
else if(a==1)
return 1;
i
value 2, it will call fibs(2). In fibs
function, else part gets executed.
else
return (fibs(a-1)+fibs(a-2));
For fibs(2)
it call recursively itself for fib(2-1)+ fibs(2-2) i.e fibs(1) and fibs(0).