Reputation: 141
I am attempting problems from Project Euler.net. The problem I am stuck on goes like this.
I have come up with the following code.
#include<iostream>
#include<cstdlib>
using namespace std;
int main() {
int a=1,b=1,c,sum=0;
while(c<4000000)
{
c=a+b;
if((c%2)==0)
sum+=c;
a=b;
b=c;
}
cout<<sum;
return 0;
}
The sum returned is always zero
. I have looked at the other solutions on StackOverflow but am not able to understand the problem in my solution. Any help appreciated.
Upvotes: 1
Views: 3992
Reputation: 17
public class Sample {
public static void main(final String args[]) {
// fibno me even terms
int a = 0, b = 1;
int temp = 0;
// print fibo below 4 million
for (int i = 0; i <= 4000000; i++) {
int c = a + b;
// System.out.println(c);
if (c % 2 == 0)
{
temp = temp + c;
// System.out.println("Even" + c);
}
a = b;
b = c;
}
System.out.println("temp value is " + temp);
}
}
Upvotes: 0
Reputation: 490108
You haven't initialized c
before entering the loop. If it contains something larger than your limit, the loop won't execute, and sum
will remain 0
after the loop terminates.
Upvotes: 5