Monday, 24 October 2016

Write a function sum_fibo(n) which sums all the even valued terms in the Fibonacci sequence till 'N'

/*
Write a function sum_fibo(n) which sums all the even valued terms in the Fibonacci sequence till 'N' where n<4*10^6
By Starting with 1 and 2, the first 10 terms will be : 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
*/


#include<stdio.h>
int sum_fibo(int n) {
 int sum=0,i;
 int f1=0, f2=1, f3;
 for(i=0; i<n; i++) {
  f3=f1+f2;
  if(f3%2==0) {
   sum = sum + f3;
  }
  f1 = f2;
  f2 = f3;
 }
 return sum;
}
int main() {
 int n;
 printf("Enter N:");
 scanf("%d", &n);
 printf("\nResult: %d", sum_fibo(n));
 return 0;
}

No comments: