Showing posts with label Fibonacci. Show all posts
Showing posts with label Fibonacci. Show all posts

Fibonacci : Sum of even-valued terms of Fibonacci Sequence



Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Source Code in C:

#include<stdio.h>
void main()
{
      long f1 = 1, f2 = 2, f3, range,sum=0;
      clrscr();
      printf("Enter the maximum range: ");
      scanf("%ld", &range);
      while(1)
      {
                f3 = f1 + f2;
                if(f3 > range)
                          break;
                if (f3%2==0)
                sum+=f3;
                if (f3==3) sum+=2;
                f1 = f2;
                f2 = f3;
      }
      printf("The sum of all even digit : %ld",sum);
      getch();
}

Answer:  4613732