Sum of Fibonacci Series
Algorithm
Input n=No of element in the series Output Sum of series of n elements Complexity O(nlogn) Fibonacci(fib,n) 1. Set sum=0; 2. If (n==0 or n==1) then 3. fib=n; 4. Sum=sum+fib; 5. Return fib.; 6. Call Fibonacci(fibA,n-2); 7. Call Fibonacci(fibB,n-1); 8. Set Fib=fibA+fibB; 9. Sum=sum+fib; 10. Return Fib; 11. Outside the function print sum.
Algorithm Description
1-5. Check whether n=0 or 1 means whether it’s a first element or second element of the series if so it set fib to 0 0r 1;Fib hold the value of the series.sum :it is a temporary variable which hold the value of sum of series elements.
6. Recursive function which recursively hold the previous of previous value of the series.
7. Recursive function which recursively hold the previous value of the series.
8. It add two values from step 6 and step 7 and give the current element of the series .
11. After function termination this line will execute and print the value of sum
C Code
#include<stdio.h>
#include<conio.h>
long int fib(long int);
int main()
{
long int sum=0;
long int k;
int i,n;
printf("\nEnter the number of element in the series : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
k=fib(i);
sum=sum+k;
}
printf("sum of %ld",sum);
return (0);
}
long int fib(long int n)
{
if(n<=1)
{
return n;
}
else
{
return fib(n-1)+fib(n-2);
}
}