# Returning the sum of even numbers

I just really cant seem to write a function that returns the sum off all the odd numbers. I do it the way I was shown but when I put it on the compilers undefined

function sum_even(arr){
var sum = 0;
for(var i = 5; i< 429; i++) {
if(i % 2 === 0) {
sum = sum + i;
}
}
return sum;
}

The way I thought it should work is i would need to make a placeholder first so I set my sum = 0. I want to return all the values that are even from the numbers 5 through 428 so I make a for loop with a conditional statement that checks if a number is even. The numbers that are even are added to sum all the way until the for loop stops at 428. So can some one help me understand why nothing is being returned. It would be a great help

It is not really a placeholder, just an initialized counter. We always start with zero when seeking a total of anything. That gives us a defined value to which we may add or subtract a sequence of numbers.

Consider that you control the loop parameters from the start. Going in we know we want to add only even numbers, so we can set it up so only even numbers are iterated over in the loop. We know that 5 is not even so we can start on the first even number after 5.

``````for (var i = 6; i < 429; i += 2) {

}
``````

Now we are counting in twoâ€™s and donâ€™t need a conditional. We can just keep adding to the accumulator, `sum`

``````    sum += i;
``````

Without seeing the actual question, we must stop here.

The instructions where simply â€śCreate a function that returns the sum of all even numbers from 3 to 462â€ť Yours is surely a much faster route, but im just not sure why mine doesnt return anything.

Not what we had above. Try modifying your loop to contain these two numbers and you should get the right answer with your code.

Printing and returning mean different things, and function and program are also two different concepts.
I think that when you say that your function doesnâ€™t return anything,
Â Â Â Â Â Â Â Â Â Â Â Â what you mean is that your program doesnâ€™t print anything.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.