IronDome - 1 year ago 126

Java Question

I am trying to find the sum of the even Fibonacci numbers up untill 4 million.

I found the numbers but i can't get them add up... in the if(n % 2 ==0) loop

`8`

34

144

610

2584

10946

46368

196418

832040

3524578

`public static void number2()`

{

int number = 40;

int a, b, c;

int numLim = 0;

a = 1;

b = 2;

while(numLim < 4000000)

{

c = a + b;

a = b;

b = c;

numLim = b;

if(numLim > 4000000)

{

break;

}

int sum = 0;

if(numLim % 2 == 0)

{

System.out.println(numLim);

sum = sum + numLim;

System.out.println("sum :" +sum);

}

}

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You must define `sum`

outside the `while`

loop, or it will become `0`

each iteration.

```
int sum = 0;
...
while ...
```

Remember not to set `sum`

to 0 each iteration.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**