I am using Dev-C++. It doesn’t show any code error, but fails to work.
It works when I try small numbers like 10 or 20
I am working on this problem :
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.
#include<stdio.h>
#include<stdlib.h>
int main()
{
const int N=100;
int a=1,b=2,i,t[N],S=0,c,j;
t[0]=1;
t[1]=2;
for(i=2;i<N;i++){
t[i]=t[i-2]+t[i-1];
if(t[i]>4000000)
{
for(j=1;j<=i-1;j++){
c=t[j]%2;
if(c==0){
S=S+t[j];
}
else {
continue;
}}
break;
}
}
printf("%d\n",S);
system("pause");
}
You don’t need an array to store all those numbers, you can get away with storing the last two terms in the sequence, since that’s all that’s need to calculate the next term.
Trying to allocate that much space on the stack is asking for trouble since the stack is a relatively limited resource.
In fact, that exact code entered into
gccon a Linux box gives me a segmentation violation when I try to run it, for precisely that reason.On top of that, your code is not getting the even valued terms, it’s getting every term, and you’re getting the first four million values, rather than the values below four million which was specified.
The sort of code you’re after would look like this:
And the output:
If you test that program by un-commenting the debug statement, you see:
and, if you add up all the even numbers at the end of those
DEBUGlines, you do indeed get the given value.