Sum all odd Fibonacci Numbers - Can anyone help me debug my code?

Sum all odd Fibonacci Numbers - Can anyone help me debug my code?
0

#1

Hello, everybody

`function sumFibs(num) {
var arr=[1,1];
var next=0;
while(next<num){
next=arr[arr.length-1]+arr[arr.length-2];
if(next%2)
arr.push(next);
}
return arr;
}
sumFibs(10);`

This is the code I can’t debug. I received a potential infinite loop error but i cannot understand why
While condition seems clear to me… could anyone explain me what’s wrong?
Thank you!

#2

One problem is the if statement on line 6:

if(next%2)

The first time entering the loop, next is equal to 0, so we go to line #5

next=arr[arr.length-1]+arr[arr.length-2];

After the above executes, next is now equal to 2
Your line 7 if evaluates to 0 (zero) which is a falsely value, so line 8 is skipped and the while asks if next is less than num. Since 2 is less than num (10) in your example we go through the same thing again. Since there are only 2 items in arr, next is going to keep being 2 forever (hence the infinite loop you have).

Now that you know what is going on with your existing code, try to figure out what to change. Try to write out your algorithm on paper first without code and then walk through an example to make sure your written steps will produce the correct answer before trying to code it in JavaScript again.

If you get stuck or do not understand what I have written here, please reply back and I will try to guide you in the right direction with small hints.

#3

Don’t forget to increment the variable in your while loop. Also console.log() often to see your results so you don’t get lost.

I found it useful to break this problem into steps, first i made sure I can actually create the Fibonacci sequence. Only then did I proceed to summing up the odd values within that sequence.

Good luck, this one was quite a challenge but you got it bro!

#4

I’ve completely misunderstood the challenge: i was searching for the array of all the odd numbers but, since the title is clear , i was told to find the sum…
Anyway, back to my misunderstood challenge, thank you for your useful explanation!
I cannot see where I get stuck and why, but all is clear now
Thank you!

#5

What is the female for “bro”? I found “sista” but it seems to have a different meaning than the one intended.

#6

Yeh that’s tough, you girls need a word too. I guess mate or friend will suffice for now!

Good luck